diff --git a/.claude/skills/describe-component/SKILL.md b/.claude/skills/describe-component/SKILL.md new file mode 100644 index 000000000..40fa79989 --- /dev/null +++ b/.claude/skills/describe-component/SKILL.md @@ -0,0 +1,222 @@ +--- +name: describe-component +description: Generate a .llm.md knowledge file for a design system component. Use this skill whenever the user wants to document a component for AI consumption, create an .llm.md file, describe a component's usage guidance, or capture "when to use / when not to use" knowledge. Also trigger when the user says "describe Button", "document Alert for AI", "create knowledge file for Dialog", "write llm.md", or references the LLM Excellence initiative for any specific component. +--- + +# Describe Component + +Help a designer enrich a design system component with semantic context that AI tools can't extract from code alone. The output is a `.llm.md` knowledge file — the bridge between what the code *is* and what the designer *intended*. + +**Why this matters for end users:** AI tools can already read props and types. But without design intent, they'll use Alert when they should use Toast, pick the wrong Button variant, or compose components in ways that break your design language. The `.llm.md` file you create here flows through MCP to every AI tool your team uses — every file you write makes every future AI interaction better. + +**The pipeline:** +``` +You (designer) + this skill + ↓ + .llm.md file (saved next to component) + ↓ + Metadata generator parses it at build time + ↓ + MCP server serves it to AI tools + ↓ + Developers, PMs, backend engineers get better AI-generated code +``` + +## Usage + +``` +/describe-component ComponentName +``` + +**Example 1:** +``` +/describe-component Button +→ Researches code + Figma → asks you about usage boundaries → writes Button.llm.md +``` + +**Example 2:** +``` +/describe-component Alert +→ Finds 6 sub-components → asks about Alert vs Toast vs Dialog boundaries → writes Alert.llm.md +``` + +## How It Works + +The skill runs in five phases. Your input is concentrated in Phases 0 and 2 — the rest is automated. + +### Phase 0: Gather Sources + +Before touching any code, ask the designer for context: + +> "I'm going to research **{ComponentName}**. Two things will help me write a better knowledge file: +> +> 1. **Figma URL** — the component's design spec (variants, states, your design notes) +> 2. **Storybook URL** — the live component page (or I can work from the stories file) +> +> If you don't have one or both, no problem — I'll work with what's available." + +The Figma URL matters because you as a designer capture intent there (spacing rules, variant restrictions, usage notes) that often doesn't make it into code. The Storybook URL shows how the implementation actually looks. Together with the source code, these three sources give a near-complete picture — the interview fills the remaining gaps. + +### Phase 1: Automated Research + +The goal is to exhaust what can be learned from code and Figma before asking the designer anything. This respects your time — no questions about things that are already documented. + +**Read the component directory** at `packages/design-system/src/components/{ComponentName}/`: + +| File | What to look for | +|------|-----------------| +| `{ComponentName}.tsx` | Props interface, JSDoc, render structure, ARIA attributes, context usage | +| `classes.ts` | CVA variants, compound variants, defaults — this is where the variant system lives | +| `types.ts` / `const.ts` | Exported types, enums, constants | +| `index.ts` | Public exports — reveals sub-component list | +| Sub-component files (`{Name}*.tsx`) | Each sub-component's props, role, slot name | +| `{ComponentName}.stories.tsx` | All stories, arg types, code patterns demonstrated | +| `{ComponentName}.figma.tsx` | Figma↔code prop mappings (if Code Connect exists) | + +**If the designer provided a Figma URL**, query the Figma MCP: +- `get_design_context` → full design spec, visual variants +- `get_screenshot` → visual reference to show back to the designer +- `get_metadata` → layer structure, auto-layout +- `get_code_connect_map` → existing Figma↔Code mappings + +**Compile a Research Brief** and present it in **designer-friendly language**. The brief should translate code findings into visual/behavioral terms the designer thinks in — not raw prop counts. + +``` +RESEARCH BRIEF: {ComponentName} +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +What I found: +- {standalone component | compound component with N parts: list them} +- {N visual variants}: {describe in design terms, e.g., "4 styles (primary, outline, ghost, secondary) × 4 colors (brand, neutral, neutral-alt, destructive) × 3 sizes"} +- {N stories in Storybook}: {list key ones, e.g., "Basic, All Variants, With Icons, Loading, Disabled, Full Width"} +- {Figma findings}: {design notes, variant structure, or "not provided"} +- {Accessibility}: {keyboard behavior, ARIA patterns found in code} +- {Restrictions}: {compound variant rules, e.g., "ghost style can't be used with destructive color"} + +What I still need from you: +- {list genuine gaps — things code and Figma couldn't tell us} +``` + +The brief should make the designer think "yes, that's right" or "no, you're missing X" — it's a checkpoint before the interview. + +### Phase 2: Iterative Interview + +This is the designer's core contribution — the knowledge that only lives in their head. The interview is a conversation, not a questionnaire. It continues until there's enough confidence to write every section of the `.llm.md` file. + +**Start with boundaries, not features.** It's much easier to say "definitely don't use this for X" than to enumerate every valid use case. Lead with exclusions — everything not excluded is implicitly valid. + +**For each question, briefly explain why it matters for AI quality** — this helps the designer give sharper, more targeted answers. + +#### Round 1 — Boundaries & Gotchas + +1. **Where NOT to use** — "Where should {ComponentName} definitely NOT be used? What are the cases where people reach for it but should use something else?" + *Why this matters: without this, AI tools will use {ComponentName} for everything that looks vaguely similar — e.g., using Alert for transient messages that should be Toasts.* + Let the designer list exclusions freely. Then clarify: "So everything not on this list is fair game?" + +2. **What surprises people** — "What's the non-obvious thing about {ComponentName}? Anything that looks like it should work a certain way but doesn't?" + *Why this matters: the AI will hit the same surprises developers do — better to document them upfront.* + +3. **Common mistakes in practice** — "When you review PRs or designs, what mistakes do you see most with {ComponentName}? Wrong style choice, wrong context, something missing?" + *Why this matters: the "Do's and Don'ts" section directly prevents repeat mistakes across the whole team.* + +4. **Key relationships** — "Which components does {ComponentName} appear with most often? Any required pairings or things that should never be combined?" + *Why this matters: AI tools compose components in isolation. This teaches them real-world groupings.* + +#### Round 2+ — Targeted Follow-ups + +After Round 1, identify what's still unclear and ask focused questions. Possible topics: + +- **Variant selection** — "When to use {variant A} vs {variant B}?" (only for components with many visual options) +- **Design constraints** — "Any hard rules? Like 'max one primary Button per screen' or 'destructive action always needs confirmation Dialog'?" +- **Edge cases** — "Long text, empty states, many items, responsive behavior — anything that needs special handling?" +- **Platform patterns** — "In the Wallarm Console specifically, are there patterns for how {ComponentName} is used?" +- **Accessibility from design perspective** — "Any rules you enforce in design review? Like 'icon-only buttons must have a text label in the tooltip'?" (The code already captures technical ARIA — this is about design-level a11y rules.) +- **Content rules** — "Any rules about the labels, text, or terminology used inside this component?" + +#### When to stop + +After each round, briefly summarize what you now know and what's still unclear — so the designer can see progress and decide whether to continue. Stop when: +- The designer signals completion ("that's it", "looks good", "nothing else") +- You can confidently write every section without guessing +- Remaining gaps are minor enough to mark as `` without undermining the file's value + +#### Interview etiquette + +- Present what you already know first — never ask what code already told you +- Accept brief answers — "same as Button" or "yeah, that's right" are perfectly valid +- If the designer says "skip" or "not sure", mark it as TODO and move on — partial knowledge files are better than no knowledge files +- Batch related questions when it makes sense, but don't overwhelm with a wall of text + +### Phase 3: Draft Generation + +Read the template from `references/llm-md-template.md` in this skill's directory. Use it as the structure, but adapt based on component type and what the interview revealed. + +Key principles: +- **"When NOT to Use" comes before "When to Use"** — boundaries first, valid cases second +- **Don't parrot TypeScript** — the variants table is not a copy of the props interface. Focus on *when* and *why* to pick each variant, not the type signature +- **Code examples from reality** — prefer patterns from actual Storybook stories over invented ones. Diverse, canonical examples beat lengthy prose +- **Composition rules are prescriptive** — state how components *must* be composed, not how they *can* be. "Alert requires AlertContent" not "Alert can optionally contain AlertContent" +- **Write for AI consumers** — clear, structured, scannable. An LLM reading this file should make correct component choices without any other context +- **Every section must earn its place** — if a section would be empty or generic for this component, omit it entirely + +### Phase 4: Stress Test + +Before showing the draft to the designer, run an automated validation. Spawn a subagent that role-plays as a developer who has **only** the `.llm.md` file — no access to code, Storybook, or Figma. Give it 6-8 ambiguous prompts that test whether the document provides enough information to make the correct decision. + +**Why this step exists:** The interview feels complete in the moment, but gaps only become visible when someone tries to *use* the document cold. This catches missing guidance before the designer signs off. + +**How to construct the test prompts:** + +Design prompts that target the highest-risk decisions — the ones where an AI is most likely to make the wrong choice: + +1. **Boundary tests** (2-3 prompts) — scenarios where the component should NOT be used but an AI might reach for it anyway. E.g., "Show the user a success message after deleting a rule" (should be Toast, not Alert). +2. **Variant selection tests** (1-2 prompts) — scenarios where the AI must pick the right variant/color/option. E.g., "Inside a delete dialog, emphasize the action is irreversible" (should be destructive color). +3. **Composition tests** (1-2 prompts) — scenarios that test layout decisions. E.g., "Put an alert in a 280px sidebar" (should use bottom actions, not top-right). +4. **Edge case tests** (1-2 prompts) — scenarios at the boundary of what the document covers. E.g., "Build an alert with a custom star icon" (icon override rules). +5. **Content test** (1 prompt) — a badly-written title that violates the content guidelines. E.g., "Please Note: The Following Items Have Been Successfully Updated" (multiple violations). + +**For each prompt, the subagent must:** +1. State what decision it would make +2. Quote the specific section that informed the decision +3. Rate confidence: HIGH / MEDIUM / LOW +4. If MEDIUM or LOW, explain what's missing + +**After the test, compile results:** +- Count HIGH / MEDIUM / LOW +- List any gaps (things the document should cover but doesn't) +- List any ambiguities (things mentioned but not clear enough) + +**Then fix the gaps** — update the `.llm.md` draft to address any MEDIUM or LOW findings before presenting to the designer. Small, targeted additions are best — don't bloat the document. + +### Phase 5: Designer Review + +Present the complete draft **along with the stress test results** to the designer: + +> "Here's the draft. I also ran a stress test — 8 ambiguous prompts against the document. Results: {X} HIGH confidence, {Y} MEDIUM, {Z} LOW. I've already fixed the gaps I found. Take a look — anything to add, correct, or emphasize?" + +Highlight which parts came from code (the AI can verify those) vs which came from the interview (the designer should validate those). Apply corrections and iterate until the designer approves. + +### Phase 6: Save & Connect + +Write the final file to: +``` +packages/design-system/src/components/{ComponentName}/{ComponentName}.llm.md +``` + +After saving, explain the downstream impact: + +> "Done. **{ComponentName}.llm.md** is saved next to the component source. Here's what happens next: +> +> - The metadata generator will parse this file at build time and include the semantic context in `dist/metadata/components.json` +> - The MCP server will serve this context to any AI tool that queries the design system +> - From now on, when anyone asks an AI 'build me a form with...' or 'show a notification...', the AI will have your design guidance to make the right choice +> +> Want to test another component, or adjust the template based on this experience?" + +## Notes + +- The `.llm.md` file is for AI consumption first, human readability second. Optimize for scannability and clear decision criteria. +- Don't duplicate what TypeScript interfaces already express. Focus on the semantic layer: when, why, how, with whom, and what to avoid. +- The "When NOT to Use" section has the highest impact — it prevents the most common AI mistake: using the wrong component for a use case. +- Keep code examples minimal but realistic. A 3-line snippet showing the right pattern beats a 30-line example. +- Partial files are fine. If the designer can't answer everything, save what you have with TODO markers. An 80% complete `.llm.md` is infinitely better than no `.llm.md`. diff --git a/.claude/skills/describe-component/references/llm-md-template.md b/.claude/skills/describe-component/references/llm-md-template.md new file mode 100644 index 000000000..c6c6a8c24 --- /dev/null +++ b/.claude/skills/describe-component/references/llm-md-template.md @@ -0,0 +1,124 @@ +# .llm.md Template Reference + +This is the standard template for component knowledge files. Adapt sections based on component type — not every section applies to every component. + +## Table of Contents + +1. [Full Template](#full-template) +2. [Template Adjustments by Type](#template-adjustments-by-type) +3. [Section Guidance](#section-guidance) + +## Full Template + +```markdown +# {ComponentName} + +> {One-line description} + +## Category +{actions | data-display | inputs | layout | loading | messaging | navigation | overlay | primitives} + +## When NOT to Use +{List of wrong use cases with correct alternatives: "→ use {Component} instead"} +{This section comes FIRST because it defines boundaries — everything not listed here is valid} + +## When to Use +{Bullet list — the positive cases, derived from what's left after exclusions + interview insights} + +## Anatomy +{For compound components: list sub-components with required/optional} +{For standalone: key visual parts (icon slot, label, etc.)} +{Skip for simple components like Badge, Text} + +## Variants & Options +| Prop | Options | Default | Notes | +|------|---------|---------|-------| +{From CVA variants in classes.ts} + +### Variant Rules +{Compound variant restrictions, e.g., "ghost + destructive is not available"} +{Skip if no compound variants} + +## Composition Patterns +### {Pattern Name} +{Description — use prescriptive language: "must", "always", "requires"} +```tsx +{Code example — prefer real patterns from stories, adapt if needed} +\``` +{Repeat for 2-4 most common patterns} + +## Accessibility +- **Keyboard:** {from code analysis} +- **ARIA:** {roles, attributes found in code} +- **Screen reader:** {from code + interview} +- **Focus:** {focus management patterns} + +## Gotchas +{Things that surprise people or behave unexpectedly — 2-4 bullets} +{E.g., "Icon-only Button requires aria-label — screen readers will announce nothing without it"} +{E.g., "ghost variant has no visible boundary — users may not realize it's clickable"} +{Omit if nothing non-obvious surfaced during interview} + +## Do's and Don'ts +| Do | Don't | +|----|-------| +{From interview + code analysis, 3-6 rows} + +## Related Components +| Component | Relationship | When to prefer | +|-----------|-------------|----------------| +{From interview + code analysis} + +## Platform Context +{Wallarm-specific usage patterns from interview} +{If no platform context gathered, omit this section entirely} + +## Tags +{Comma-separated searchable tags} +``` + +## Template Adjustments by Type + +| Type | Adjustments | +|------|------------| +| **Standalone** (Button, Badge) | Skip Anatomy if trivial | +| **Compound** (Alert, Dialog) | Expand Anatomy, emphasize required vs optional children and ordering | +| **Layout** (Flex, Stack) | Focus on spacing patterns, responsive behavior | +| **Input** (Input, Select) | Focus on form integration, Field context, validation | +| **Data Display** (Table, Code) | Focus on data formatting, loading/empty states | +| **Overlay** (Dialog, Popover) | Focus on trigger patterns, stacking, dismissal | + +## Section Guidance + +### "When NOT to Use" comes before "When to Use" + +This is intentional. It's easier for the expert to define what a component is NOT for, and everything else is implicitly fair game. The negative list is also more actionable for AI consumers — it prevents the most common misuses. + +### Code Examples in Composition Patterns + +Prefer real patterns from Storybook stories over invented ones. If a story shows a pattern well, adapt it. If not, synthesize from code analysis + interview. Keep examples minimal — just enough to show the composition, not a full page. + +Use **prescriptive language** in composition descriptions. Instead of "Alert can contain AlertContent and AlertIcon," write "Alert requires AlertContent. AlertIcon is optional but recommended for all color variants except neutral." This is the shadcn/skills pattern — enforcement, not suggestion. + +### Gotchas + +This section captures what surprises people — the non-obvious behaviors, the edge cases that bite developers on first use. It's sourced from the interview question "what trips people up?" rather than a formal bug list. + +Good gotchas are specific and actionable: +- "Icon-only Button requires `aria-label` — screen readers announce nothing without it" +- "Toast auto-dismisses after 5 seconds — don't use for errors that need user acknowledgment" +- "Select with more than ~50 options becomes sluggish — use a searchable pattern instead" + +Bad gotchas are generic or obvious: +- "Make sure to pass required props" (obvious) +- "Test on different screen sizes" (generic advice, not component-specific) + +If the interview didn't surface anything surprising, omit the section entirely. + +### Platform Context + +Only include this section if the interview yielded Wallarm-specific patterns. Don't fill it with generic advice — it should contain insights like "In the Wallarm Console, the Delete Rule button always uses `color='destructive'` and opens a confirmation Dialog." + +### Tags + +Think about what an AI tool would search for. Include: the component's role (e.g., "cta", "form-control"), related concepts ("notification", "feedback"), and synonyms ("modal" for Dialog, "dropdown" for Select). diff --git a/.claude/skills/describe-component/references/research-ai-component-docs.md b/.claude/skills/describe-component/references/research-ai-component-docs.md new file mode 100644 index 000000000..af762e7a6 --- /dev/null +++ b/.claude/skills/describe-component/references/research-ai-component-docs.md @@ -0,0 +1,174 @@ +# Research: AI-Consumable Component Documentation + +Best practices gathered from industry leaders and emerging standards (March 2026). + +## Table of Contents + +1. [GOV.UK Design System — Documentation Structure](#govuk-design-system) +2. [shadcn/skills — AI Knowledge Packages](#shadcnskills) +3. [Anthropic — Context Engineering](#anthropic-context-engineering) +4. [v0 by Vercel — Registry-Based Context](#v0-registry) +5. [Key Takeaways for .llm.md Files](#key-takeaways) + +--- + +## GOV.UK Design System + +**Source:** [How we document components and patterns](https://designnotes.blog.gov.uk/2018/11/05/how-we-document-components-and-patterns-in-the-gov-uk-design-system/) + +The GOV.UK Design System is widely regarded as the gold standard for component documentation. Every component follows the same content pattern: + +1. **What it is** — title, live example, short description +2. **When to use it** — situations where the component should be used +3. **When not to use it** — wrong use cases with alternatives suggested +4. **How it works** — functionality, implementation, adaptation guidance +5. **Research** — evidence and user research behind design decisions +6. **Known issues** — unresolved problems or limitations, documented honestly + +### Writing principles + +- **Consistency** — all components follow the same structure so users know what to expect +- **Clarity** — clear, inclusive language over technical jargon +- **Usefulness** — "everything we say has a clear point" — no filler +- **Honesty** — gaps and known issues are documented openly; teams don't need perfection before publication + +### What we adopted + +- The "When NOT to Use" before "When to Use" ordering (boundaries-first approach) +- The consistent structure across all components +- The principle that every section must earn its place + +### What we should add + +- **Known Issues / Gotchas** section — GOV.UK documents these openly. AI tools benefit from knowing component quirks upfront rather than discovering them at runtime +- **Research/evidence notes** — when a "don't use X for Y" rule exists, briefly noting *why* helps AI tools make better judgment calls in edge cases + +--- + +## shadcn/skills + +**Source:** [shadcn/ui Skills docs](https://ui.shadcn.com/docs/skills) | [March 2026 changelog](https://ui.shadcn.com/docs/changelog/2026-03-cli-v4) + +shadcn/skills (launched March 2026) is the closest parallel to what we're building. It provides AI agents with a "specialized context layer" about the design system, reducing hallucinations and mistakes. + +### How it works + +1. **Project detection** — finds `components.json` to understand project setup +2. **Context injection** — runs `shadcn info --json` to extract framework, Tailwind version, installed components, icon library, path aliases +3. **Pattern enforcement** — AI follows composition rules (e.g., "use FieldGroup for forms", semantic color usage) +4. **Component discovery** — before generating code, the agent uses `shadcn docs`, `shadcn search`, or MCP tools to find relevant documentation + +### What it includes + +- Full CLI reference (init, add, search, view, docs, diff, info, build) +- Theming guidance (CSS variables, OKLCH colors, dark mode, custom variants) +- Registry authoring details for custom component registries +- MCP server setup for component search and installation + +### Key insight + +shadcn/skills focuses on **composition rules and pattern enforcement**, not just "here's what exists." The skill doesn't just list components — it tells the agent *how components must be combined*. Our `.llm.md` files should do the same: not just describe variants, but enforce how they compose. + +### What we adopted + +- The skill-as-knowledge-package pattern (our describe-component skill) +- Pattern enforcement language in composition sections +- MCP as a discovery mechanism alongside file-based knowledge + +--- + +## Anthropic Context Engineering + +**Source:** [Effective context engineering for AI agents](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) + +Anthropic's engineering team published a guide on structuring context for AI agents. The core principle: + +> "Find the smallest set of high-signal tokens that maximize the likelihood of your desired outcome." + +### Key principles + +- **Treat context as a finite resource** — every token depletes the model's "attention budget." Context rot occurs as context grows, creating diminishing returns. +- **Minimum Viable Context (MVC)** — start minimal, expand empirically based on observed failure modes. Minimal doesn't mean short — it means every token pulls its weight. +- **Goldilocks prompts** — avoid overly rigid if-then logic (brittle) and vague guidance (assumes shared understanding). Explain the *why* so the model can generalize. +- **Examples > exhaustive rules** — diverse, canonical examples showing expected behavior beat lengthy edge-case lists. +- **Just-in-time retrieval** — don't pre-load everything. Retrieve context when needed, not upfront. + +### Structural recommendations + +- Organize into distinct sections using XML tags or Markdown headers +- Keep tools minimal and non-overlapping in function +- Make tool descriptions unambiguous enough that a human could definitively choose the right one + +### Common mistakes + +1. **Bloated tool sets** with ambiguous decision points +2. **Over-engineering prompts** with complex brittle logic instead of flexible heuristics +3. **Stuffing edge cases** into prompts to address every possible rule +4. **Pre-loading all relevant data** upfront rather than retrieving just-in-time + +### What we adopted + +- NOT repeating TypeScript interface details in `.llm.md` (that's in code — high-signal tokens only) +- Omitting sections that would be empty or generic rather than filling with filler +- Using progressive disclosure (SKILL.md → references/ → component files) + +--- + +## v0 Registry + +**Source:** [v0 Design Systems docs](https://v0.app/docs/design-systems) + +v0 by Vercel uses the Shadcn Registry as its distribution mechanism — "a distribution specification designed to pass context from your design system to AI Models." + +### What v0 consumes + +- **Component source code** — direct access to customized component code +- **Design tokens** — CSS variables for colors, fonts, spacing (shadcn/ui CSS variables standard) +- **Visual references** — metadata, file content, and styles passed via API +- **Registry dependencies** — component relationships and dependency chains + +### How it works + +Each registry entry follows the registry-item JSON specification with source code files, file paths, target paths, and registry dependencies. The "Open in v0" button triggers an API call with all metadata, giving v0 a "starting point and context on your specific design system." + +### Key insight + +v0 proves that AI tools need **both structural data (code, types) and semantic context (how things should be used)** to generate good output. The registry handles structural; our `.llm.md` files handle semantic. They're complementary layers. + +### Limitation noted + +v0 is "specifically trained on the default implementations" of shadcn/ui — heavily customized primitives may not work as well. This underscores why **custom semantic documentation** (our `.llm.md` approach) matters for non-standard design systems. + +--- + +## Key Takeaways + +### For our `.llm.md` template + +| Principle | Source | How we apply it | +|-----------|--------|----------------| +| Boundaries first | GOV.UK | "When NOT to Use" comes before "When to Use" | +| Known issues section | GOV.UK | Add a "Gotchas" section for component quirks | +| Composition enforcement | shadcn/skills | Patterns section should say "must" not just "can" | +| Minimum viable context | Anthropic | Don't repeat what TypeScript already expresses | +| Examples over rules | Anthropic | 2-4 diverse code examples beat a paragraph of rules | +| Honest about gaps | GOV.UK | Mark unknowns as TODO rather than inventing answers | +| Semantic + structural | v0 | `.llm.md` is the semantic layer; code is the structural layer | + +### On the agent question + +- **One skill is enough for now.** shadcn/skills is a single skill, not a skill+agent pair. +- The describe-component workflow is inherently interactive (needs human input) = skill pattern. +- An agent makes sense later for automated tasks: "review all `.llm.md` for consistency", "auto-update when code changes." +- Starting with one skill keeps complexity low for team evaluation. + +### On distribution + +The industry is converging on three channels (we're already planning all three): +1. **MCP** — structured data, search, suggestions (our `packages/mcp/`) +2. **Files** — detailed knowledge, reference material (our `.llm.md` + `guidelines/`) +3. **Skills** — complex workflows, multi-step tasks (our `.claude/skills/`) + +--- + +*Research conducted March 18, 2026. Sources may have been updated since.* diff --git a/.cursorrules b/.cursorrules new file mode 100644 index 000000000..a95d252da --- /dev/null +++ b/.cursorrules @@ -0,0 +1,53 @@ +## Project Context + +You are working on the Wallarm Design System (WASD) — a production React component library with 56 components, MCP server integration, and comprehensive tooling. + +## Current Initiative: LLM Excellence + +We are making this design system LLM-friendly so that designers, PMs, frontend and backend developers can vibe-code consistent, on-brand interfaces using AI tools. + +**Read `docs/WASD-LLM-Excellence-Framework.md` for the full strategic plan.** This is the master document that describes: +- Current state assessment and gap analysis +- Three-tier framework (Components → Guidelines → Platform) +- The `/describe-component` skill design (Section 4.5) — the cornerstone tool for creating .llm.md files +- Enhanced MCP schema proposals +- Skills and agents roadmap (10 new skills) +- Implementation phases and PR sequence + +**Read `docs/WASD-Workflow-Guide.md` for the Git workflow** — branch naming, PR sequence, task ownership. + +## Key Architecture Facts + +- **56 components** in `packages/design-system/src/components/` +- **CVA** (class-variance-authority) for all variants, defined in `classes.ts` +- **Ark UI** headless primitives for accessible foundations +- **Compound component pattern** with Context + TestIdProvider +- **MCP server** in `packages/mcp/` — serves component metadata to AI tools +- **Metadata generation** via ts-morph AST parsing at build time → `dist/metadata/components.json` +- **Figma Code Connect** in `.figma.tsx` files per component +- **Storybook 10** with MCP addon at `localhost:6006/mcp` + +## What We're Building + +### .llm.md Files +Per-component knowledge files placed next to the component source. These are the **authoring format** — they get parsed by the metadata generator and served through MCP to end users. They contain: when to use, when NOT to use, composition patterns, accessibility notes, do's/don'ts, related components, platform context. + +Standard template is in Section 4.5 of the Framework doc → Phase 3: Draft Generation. + +### Guidelines (in `guidelines/` directory) +Above-component knowledge: UX copywriting, data display patterns, form patterns, page layouts, states, navigation, accessibility, iconography, Wallarm platform context. + +### Skills (in `.claude/skills/`) +- `/describe-component` — generates .llm.md files via Figma + Storybook + human interview +- `/ux-copy`, `/data-format`, `/form-pattern`, `/page-layout`, `/a11y-check`, `/states`, etc. + +### MCP Enhancements +New tools: `suggest_component`, `get_pattern`, `get_guideline`. Extended schema with `whenToUse`, `composition`, `accessibility`, `tags`, `category`. + +## Rules + +- Import components from `@wallarm-org/design-system` or `@wallarm-org/design-system/{Component}` +- Never use raw HTML when a DS component exists +- Use semantic design tokens, never raw colors or spacing +- Follow conventional commits: `feat:`, `docs:`, `chore:` +- All component files follow the patterns in `.claude/rules/` diff --git a/docs/WASD-LLM-Excellence-Framework.md b/docs/WASD-LLM-Excellence-Framework.md new file mode 100644 index 000000000..feceea089 --- /dev/null +++ b/docs/WASD-LLM-Excellence-Framework.md @@ -0,0 +1,1067 @@ +# Wallarm Design System: LLM Excellence Framework + +## Strategic Research & Implementation Roadmap + +**Author:** Claude (AI Research Assistant) for Artem Miskevich, Head of Design & DS Manager +**Date:** March 17, 2026 +**Scope:** Full discovery, gap analysis, and action plan for making WASD (Wallarm Design System) the gold standard for LLM-friendly design systems + +--- + +## 1. Executive Summary + +Wallarm Design System (WASD) is already **ahead of 95% of design systems** in terms of LLM-readiness. You have a working MCP server, automated metadata generation via AST parsing, specialized Claude agents, skills, and rules. This is a strong foundation. + +However, the current system captures **structural information** (props, types, variants) but largely misses **semantic knowledge** — the "why," "when," and "how" that separates competent code generation from *excellent, consistent, on-brand* interface building. The system knows **what** components exist but doesn't fully convey **why** to choose one over another, **how** to compose them into real interfaces, or **what rules** govern the writing, data formatting, and UX patterns above the component level. + +This document proposes a layered framework — **WASD LLM Excellence** — that transforms your design system from a component catalog into a comprehensive AI-consumable knowledge base for building production-quality Wallarm interfaces. + +--- + +## 2. Current State Assessment + +### 2.1 What's Already Built (Strengths) + +**Architecture & Infrastructure:** +- Monorepo (Turborepo + pnpm) with 56 components, clean separation of concerns +- `@wallarm-org/mcp` server (v0.1.0) — 4 tools (`search_component`, `get_component`, `search_token`, `get_token_category`) + 3 resources +- `@wallarm-org/mcp-core` — Zod schemas for type-safe metadata +- Automated metadata generation via ts-morph AST parsing at build time +- Storybook v10 with MCP addon +- Figma Code Connect integration + +**AI Agent Infrastructure:** +- `CLAUDE.md` — project-level instructions (7KB, well-structured) +- `AGENTS.md` — routing to 4 specialized agents (Design System, Test, Component Architect, CI/CD) +- `.claude/agents/` — detailed agent prompts +- `.claude/rules/` — component-development, coding-standards, test-id, e2e rules +- `.claude/skills/` — `/new-component`, `/review-pr`, `/filter-field-design` +- Ralph autonomous agent for PR completion + +**Component Quality:** +- CVA (class-variance-authority) for all variant definitions +- Ark UI headless primitives for accessible foundations +- Compound component patterns with Context +- Test ID cascading system +- `data-slot` attributes on every component +- Full Tailwind CSS v4 token system + +### 2.2 Current LLM-Readiness Score: ~60/100 + +| Dimension | Score | Status | +|-----------|-------|--------| +| Component API documentation (props, types) | 9/10 | Excellent | +| Variant system documentation | 7/10 | Good (dynamic variants lost) | +| Design tokens accessibility | 8/10 | Good | +| MCP server functionality | 8/10 | Good | +| Usage examples from Storybook | 6/10 | Extracted but raw, no semantic context | +| "When to use" guidance per component | 2/10 | Almost absent from metadata | +| Composition patterns & rules | 2/10 | Not captured in metadata | +| Accessibility guidance | 2/10 | In code but not in AI-consumable form | +| UX copywriting standards | 0/10 | Does not exist | +| Data display patterns (dates, numbers, statuses) | 1/10 | Utilities exist, no guidelines | +| Interface assembly patterns (page layouts, flows) | 0/10 | Does not exist | +| Cross-component consistency rules | 1/10 | Implicit, not codified | +| Onboarding for non-designers (PMs, backend devs) | 1/10 | Not designed for this audience | + +### 2.3 Gap Analysis: What's Missing for True LLM Excellence + +**Layer 1 — Component Knowledge Gaps:** +- No "when to use" / "when NOT to use" descriptions per component +- No composition patterns (which sub-components are required vs optional, child ordering) +- No accessibility profiles (ARIA roles, keyboard patterns, screen reader behavior) +- Sub-component descriptions not captured in metadata +- Compound variants (CVA compoundVariants) not documented +- Dynamic variants (e.g., Badge colors) show as empty arrays +- Prop relationships (controlled/uncontrolled pairs, mutual exclusions) not expressed +- No component decision trees ("need a notification? → transient: Toast, persistent: Alert, blocking: Dialog") + +**Layer 2 — Above-Component Knowledge Gaps:** +- No UX copywriting guidelines (tone, voice, error messages, empty states, CTAs) +- No data display standards (date formats, number formats, currency, percentages, durations) +- No status/state display conventions (how to show loading, error, empty, success consistently) +- No page layout patterns (common page structures, spacing rhythms, content hierarchies) +- No navigation patterns (breadcrumb rules, tab usage, sidebar conventions) +- No form patterns (validation messaging, field ordering, progressive disclosure) +- No responsive behavior guidelines + +**Layer 3 — Platform Knowledge Gaps:** +- No Wallarm-specific product context (what the platform does, user personas, domain terminology) +- No existing UI patterns from the product (how existing pages are structured) +- No iconography guidelines (when to use which icon, icon + text vs icon-only rules) +- No color usage guidelines beyond tokens (when to use brand vs neutral, semantic color rules) + +--- + +## 3. The LLM Excellence Framework + +### 3.1 Architecture Overview + +The framework is organized into **three tiers** that progressively enrich the AI's understanding: + +``` +┌─────────────────────────────────────────────────────────┐ +│ TIER 3: PLATFORM │ +│ Product context, domain knowledge, existing patterns │ +├─────────────────────────────────────────────────────────┤ +│ TIER 2: GUIDELINES │ +│ UX writing, data patterns, layouts, forms, a11y │ +├─────────────────────────────────────────────────────────┤ +│ TIER 1: COMPONENTS │ +│ Enhanced metadata, composition, decision trees │ +└─────────────────────────────────────────────────────────┘ +``` + +### 3.2 Delivery Mechanisms + +The framework leverages multiple delivery channels, each with different strengths: + +| Mechanism | Best For | Consumed By | Already Exists? | +|-----------|----------|-------------|-----------------| +| **MCP Server** (enhanced) | Component API, tokens, search | All AI tools (Claude, Cursor, Windsurf) | Yes, needs enhancement | +| **Claude Skills** (new) | Complex workflows, multi-step tasks | Claude Code, Cowork | Partially (3 skills) | +| **CLAUDE.md** (enhanced) | Project context, high-level rules | Claude Code sessions | Yes, needs expansion | +| **Markdown knowledge base** | Detailed guidelines, patterns | AI tools reading files | No | +| **Cursor/Windsurf rules** | Editor-specific behavior | Cursor, Windsurf | No | +| **Component .md files** | Per-component deep knowledge | AI tools + humans | No | +| **Enhanced metadata schema** | Structured component data | MCP server | Partial | + +### 3.3 Key Design Principle: Progressive Disclosure + +Not everything should be in every AI prompt. The system should be designed so that: + +1. **Always available** (in CLAUDE.md / .cursorrules): High-level principles, file references, component list +2. **On-demand via MCP**: Component details, tokens, search +3. **Deep-dive via skills**: Complex workflows (building a form, creating a page layout) +4. **Reference via .md files**: Detailed guidelines that skills and agents can read when needed + +This prevents context window bloat while ensuring depth is always accessible. + +--- + +## 4. Tier 1: Enhanced Component Knowledge + +### 4.1 Component Knowledge Files + +**Deliverable:** One `.llm.md` file per component (or per component group) in the component directory. + +**Why `.llm.md`?** These files are specifically for AI consumption. They won't clutter human docs, can be parsed by the metadata generator, and are easy to maintain alongside component code. + +**Structure for each component file:** + +```markdown +# Button + +## When to Use +- Primary actions on a page (Submit, Save, Create) +- Secondary actions that need visual weight (Cancel, Reset) +- Navigation actions that look like actions (not links) + +## When NOT to Use +- Navigation between pages → use Link +- Toggling a boolean state → use Switch or ToggleButton +- Actions in a menu → use DropdownMenu items +- Icon-only compact actions → use ToggleButton with icon + +## Composition +Required: Button is a standalone component, no sub-components needed. +With icons: Place icon before text for leading, after for trailing. +Icon-only: Pass only an icon child; aria-label is REQUIRED. + +## Accessibility +- Keyboard: Enter/Space activates +- Always has accessible name (text content or aria-label) +- Disabled buttons are focusable but not actionable +- Loading state: aria-busy="true", button is disabled + +## Common Patterns +### Form Submit Button +\`\`\`tsx + +\`\`\` + +### Destructive Action with Confirmation +\`\`\`tsx + +\`\`\` + +### Button Group (Primary + Secondary) +\`\`\`tsx + + + + +\`\`\` + +## Do's and Don'ts +- DO: Use `color="destructive"` for dangerous actions +- DO: Use `variant="outline"` or `ghost` for secondary actions +- DON'T: Put two `variant="primary"` buttons side by side +- DON'T: Use Button for navigation (use Link with asChild) +- DON'T: Disable a button without explaining why (use tooltip) +``` + +**Scope:** Create `.llm.md` for every component (56 files). Prioritize by usage frequency. + +### 4.2 Enhanced Metadata Schema + +**Deliverable:** Extend `mcp-core` schema and metadata parsers. + +New fields to add to `ComponentMetadata`: + +```typescript +// In mcp-core/src/schema.ts +const componentMetadataSchema = z.object({ + // ... existing fields ... + + // NEW: Usage guidance + whenToUse: z.string().optional(), // Parsed from .llm.md "When to Use" + whenNotToUse: z.string().optional(), // Parsed from .llm.md "When NOT to Use" + + // NEW: Composition + composition: z.object({ + requiredChildren: z.array(z.string()).optional(), + optionalChildren: z.array(z.string()).optional(), + childOrdering: z.string().optional(), + pattern: z.enum(['standalone', 'compound-required', 'compound-optional', 'wrapper']).optional(), + }).optional(), + + // NEW: Accessibility + accessibility: z.object({ + ariaRoles: z.array(z.string()).optional(), + keyboardPattern: z.string().optional(), + screenReaderNotes: z.string().optional(), + }).optional(), + + // NEW: Related components + relatedComponents: z.array(z.object({ + name: z.string(), + relationship: z.enum(['alternative', 'companion', 'parent', 'child']), + note: z.string().optional(), + })).optional(), + + // NEW: Tags for better search + tags: z.array(z.string()).optional(), + + // NEW: Category + category: z.enum([ + 'actions', 'data-display', 'inputs', 'layout', + 'loading', 'messaging', 'navigation', 'overlay', 'primitives' + ]).optional(), +}) +``` + +New fields for `SubComponentMetadata`: + +```typescript +const subComponentMetadataSchema = z.object({ + name: z.string(), + description: z.string().optional(), // NEW: Parse from JSDoc + required: z.boolean().optional(), // NEW: Is this sub-component required? + props: z.array(propMetadataSchema), +}) +``` + +### 4.3 Component Decision Trees + +**Deliverable:** A new MCP tool `suggest_component` that takes a use case description and returns the best component. + +```typescript +// New tool: suggest_component +Input: { useCase: string } // e.g., "show a success message after form submission" +Output: Ranked suggestions with reasoning + +// Example output: +1. Toast (score: 95) — Best for transient success feedback that auto-dismisses +2. Alert (score: 60) — Good for persistent success messages in page context +3. Dialog (score: 20) — Overkill for simple success feedback +``` + +This tool would use the `whenToUse` / `whenNotToUse` fields plus component tags and categories for intelligent matching. + +### 4.4 New MCP Tool: `get_pattern` + +```typescript +// New tool: get_pattern +Input: { pattern: string } // e.g., "form", "data-table-page", "confirmation-dialog" +Output: Complete pattern with component composition, code example, and guidelines +``` + +### 4.5 The `/describe-component` Skill — Automated .llm.md Generator + +This is the **cornerstone skill** of the entire framework. Instead of manually writing 56+ `.llm.md` files from scratch, this skill acts as an intelligent interviewer and researcher that **gathers information from three sources** — Figma, Storybook, and the human expert (you) — and synthesizes it into a standardized, high-quality knowledge file. + +#### Why This Skill Is Critical + +Writing a good `.llm.md` file requires knowledge that lives in three different places: + +| Knowledge Source | What It Knows | How to Access | +|-----------------|---------------|---------------| +| **Figma** | Design intent, visual variants, spacing, states, edge cases, designer notes | Figma MCP (`get_design_context`, `get_metadata`, `get_variable_defs`, `get_code_connect_map`) | +| **Storybook + Code** | Implementation reality, props API, variant system, actual examples, accessibility attributes | Storybook MCP + reading `.tsx`, `.stories.tsx`, `classes.ts` files | +| **Human Expert (you)** | Design rationale, "when to use" decisions, cross-component relationships, product context, common mistakes, edge case gotchas | Interactive interview | + +No single source has the full picture. The skill merges all three. + +#### Skill Workflow: 5 Phases + +``` +┌──────────────────────────────────────────────────────────────┐ +│ PHASE 1: AUTOMATED RESEARCH (no human input needed) │ +│ ┌─────────────┐ ┌──────────────┐ ┌────────────────────┐ │ +│ │ Read Code │ │ Query Figma │ │ Read Storybook │ │ +│ │ .tsx files │ │ MCP tools │ │ stories + docs │ │ +│ │ classes.ts │ │ screenshots │ │ examples + args │ │ +│ │ types.ts │ │ variants │ │ interactions │ │ +│ └──────┬───────┘ └──────┬───────┘ └─────────┬──────────┘ │ +│ └─────────────────┼─────────────────────┘ │ +│ ▼ │ +│ ┌────────────────────────┐ │ +│ │ Compiled Research │ │ +│ │ Brief (internal) │ │ +│ └────────────┬───────────┘ │ +├───────────────────────────┼──────────────────────────────────┤ +│ PHASE 2: SMART INTERVIEW (interactive, 3-4 questions) │ +│ ▼ │ +│ "I've analyzed Button from Figma and Storybook. Here's │ +│ what I already know: [summary]. Now I need your input on │ +│ a few things I can't determine from code alone..." │ +│ │ +│ Q1: Usage decisions (when to use / not use) │ +│ Q2: Common mistakes & gotchas │ +│ Q3: Cross-component relationships │ +│ Q4: Product-specific context │ +├──────────────────────────────────────────────────────────────┤ +│ PHASE 3: DRAFT GENERATION │ +│ → Generates complete .llm.md following standard template │ +│ → Presents draft for review │ +├──────────────────────────────────────────────────────────────┤ +│ PHASE 4: REFINEMENT INTERVIEW (optional, 1-2 questions) │ +│ "Here's the draft. Anything to add or correct?" │ +│ → Human reviews, adds nuances, fixes inaccuracies │ +├──────────────────────────────────────────────────────────────┤ +│ PHASE 5: FINALIZE & SAVE │ +│ → Writes final .llm.md to component directory │ +│ → Optionally updates metadata schema if new patterns found │ +└──────────────────────────────────────────────────────────────┘ +``` + +#### Phase 1: Automated Research (Detail) + +The skill reads everything it can **before asking the human a single question**. This respects the expert's time — instead of asking "what props does Button have?" (which code already knows), it asks only what code *can't* tell us. + +**From Source Code** (reading files directly): +- `Button.tsx` → props interface, JSDoc comments, render structure, ARIA attributes, ref forwarding +- `classes.ts` → all CVA variants, compound variants, default values +- `types.ts` → exported type definitions, enum values +- `index.ts` → what's exported, sub-component list +- `context.ts` / `hooks.ts` → internal state patterns, context dependencies + +**From Figma MCP** (via available tools): +- `get_design_context(fileKey, nodeId)` → full design spec, visual variants, spacing, padding +- `get_metadata(fileKey, nodeId)` → layer structure, auto-layout rules, constraints +- `get_screenshot(fileKey, nodeId)` → visual reference for understanding design intent +- `get_variable_defs(fileKey, nodeId)` → design tokens used by this component +- `get_code_connect_map(fileKey, nodeId)` → existing Figma↔Code mappings from `.figma.tsx` + +**From Storybook** (reading story files + optionally Storybook MCP): +- `Button.stories.tsx` → all story examples, arg types, doc descriptions +- Storybook MCP at `localhost:6006/mcp` → interactive docs, rendered examples + +**The skill compiles a Research Brief** — an internal summary like: + +``` +RESEARCH BRIEF: Button +━━━━━━━━━━━━━━━━━━━━━ +Props: 12 (variant, color, size, disabled, loading, asChild, ...) +Variants: 3 axes (variant: 4 options, color: 4 options, size: 3 options) +Compound variants: 8 (disable certain color+variant combos) +Sub-components: None (standalone) +Figma variants: 48 combinations in Figma file +Figma notes: "Use Primary/Brand for main CTA, limit to 1 per screen" +Code Connect: Maps Figma "Type" → variant, "Size" → size, "State" → loading +Storybook examples: 10 stories (Basic, Variants, Sizes, Disabled, Loading, Icons, Badge, IconOnly, LinkAsButton, FullWidth) +Accessibility: No explicit ARIA roles in code, keyboard handling via native + + +``` + +## Accessibility +- Keyboard: {from code analysis} +- ARIA: {from code + interview} +- Screen reader: {from code + interview} +- Focus: {from code analysis} + +## Do's and Don'ts +| Do | Don't | +|----|-------| +| Use `color="destructive"` for dangerous actions | Put two primary buttons side by side | +| Use `variant="outline"` for secondary actions | Use Button for page navigation | +| ... | ... | + +## Related Components +| Component | Relationship | When to prefer | +|-----------|-------------|----------------| +| Link | Alternative | For navigation actions | +| ToggleButton | Alternative | For boolean toggles | +| Dialog | Companion | Often used in Dialog footer | +| ... | ... | ... | + +## Platform Context +{Wallarm-specific usage patterns from interview Q6} + +## Tags +{Searchable tags: action, cta, submit, form, interactive} +``` + +#### Phase 4 & 5: Refinement & Save + +The skill presents the draft and asks: "Here's what I've put together. Anything to add, correct, or emphasize?" After the human approves (or provides corrections), the file is saved to the component directory. + +#### Skill Invocation Examples + +``` +User: /describe-component Button +Agent: [reads code, queries Figma MCP, reads stories] + "I've analyzed Button. Here's what I found: [brief]. + Now 4 questions for you..." + +User: /describe-component Alert +Agent: [reads code — finds compound component with 6 sub-components] + [queries Figma — finds design notes about color usage] + "Alert is a compound component. I found 6 sub-components and + 5 color variants. Here's what I already know: [brief]. + I have specific questions about required vs optional children + and your rules for choosing Alert vs Toast vs Dialog..." + +User: /describe-component Table +Agent: [reads code — finds complex component with virtualization, TanStack integration] + [queries Figma — finds multiple table patterns] + "Table is your most complex component. I found column visibility, + virtualization, sorting, and 12 sub-components. This will need + a more detailed interview. Let's start with the most common + table patterns in Wallarm Console..." +``` + +#### Batch Mode + +For efficiency, the skill supports a batch mode to describe multiple related components: + +``` +User: /describe-component --batch inputs +Agent: "I'll create .llm.md files for all input components: + Input, Textarea, NumberInput, Select, Checkbox, Radio, + Switch, DateInput, DateRangeInput, TimeInput. + I'll research all of them first, then interview you + about the group — many questions overlap across inputs." +``` + +This is dramatically faster than doing each one individually, because questions like "what are your form validation patterns?" apply to all input components. + +#### Template Variants + +The standard template adapts based on component type: + +| Component Type | Template Adjustments | +|---------------|---------------------| +| **Standalone** (Button, Badge) | No anatomy section, focus on variant selection | +| **Compound** (Alert, Dialog) | Expanded anatomy with required/optional children | +| **Layout** (Flex, Stack) | Focus on spacing patterns, responsive behavior | +| **Input** (Input, Select) | Focus on form integration, validation, Field context | +| **Data Display** (Table, Code) | Focus on data formatting, loading states, empty states | +| **Overlay** (Dialog, Drawer, Popover) | Focus on trigger patterns, stacking, dismissal | + +--- + +## 5. Tier 2: Above-Component Guidelines + +This is where you go from "correct components" to "correct interfaces." Each guideline becomes a markdown file in a `/guidelines/` directory AND a Claude skill for active enforcement. + +### 5.1 UX Copywriting Guidelines + +**File:** `guidelines/ux-copywriting.md` +**Skill:** `/ux-copy` — Reviews and generates UI text following Wallarm voice & tone + +**Contents should cover:** + +- **Voice & Tone**: Wallarm's personality in UI text (professional, clear, security-focused) +- **Capitalization rules**: Title Case for headings, Sentence case for labels, buttons, etc. +- **Button labels**: Action verbs ("Save", "Create Rule", "Delete"), never generic ("OK", "Submit", "Click Here") +- **Error messages pattern**: What happened → Why → How to fix. Example: "Unable to save the rule. The IP range overlaps with an existing rule. Remove the conflicting range or edit the existing rule." +- **Empty states**: Explain what will appear here + provide action. Example: "No rules configured yet. Create your first rule to start filtering traffic." +- **Confirmation dialogs**: Question format with clear consequences. Example: "Delete this rule? All traffic matching this rule will no longer be filtered. This action cannot be undone." +- **Loading states**: "Loading rules...", "Analyzing traffic...", never just "Loading..." +- **Success messages**: Confirm what happened. "Rule created successfully" not just "Success" +- **Placeholder text**: Descriptive, not generic. "e.g., 192.168.1.0/24" not "Enter value" +- **Tooltips**: Brief, informative, no period at end +- **Truncation rules**: When to truncate, ellipsis placement, tooltip on hover + +### 5.2 Data Display Patterns + +**File:** `guidelines/data-display.md` +**Skill:** `/data-format` — Enforces consistent data formatting + +**Contents should cover:** + +- **Dates**: ISO 8601 for APIs, "Mar 17, 2026" for UI, "2 hours ago" for recent events, always show timezone for absolute times +- **Numbers**: Use `abbreviateNumber()` utility for large numbers (1.2K, 3.4M), use locale-aware formatting for precision numbers +- **Percentages**: One decimal max (99.9%), show direction (↑ 12.3%), use color coding (green for positive, red for negative) +- **Durations**: "2h 30m" for short, "3 days" for longer, "< 1 min" for very short +- **IP addresses**: Monospace font (Code component), truncate with tooltip for ranges +- **Status indicators**: Badge component with semantic colors (green=active, red=blocked, amber=warning, gray=inactive) +- **Currency**: Always show currency code, locale-aware formatting +- **File sizes**: Binary units (KB, MB, GB), one decimal max +- **Counts with zero state**: "0 rules" not "No rules" in data contexts (tables, badges) +- **Timestamps in tables**: Consistent format across all tables, relative times with absolute on hover + +### 5.3 Form Patterns + +**File:** `guidelines/forms.md` +**Skill:** `/form-pattern` — Guides consistent form construction + +**Contents:** + +- **Field ordering**: Most important first, related fields grouped, progressive disclosure for advanced options +- **Validation timing**: Validate on blur for individual fields, on submit for cross-field validation +- **Error display**: Inline errors below fields (Field component), summary at top for multiple errors +- **Required vs optional**: Mark optional fields (not required ones — most should be required) +- **Field widths**: Match expected input length (IP field narrower than description field) +- **Button placement**: Primary action right-aligned, Cancel before Submit +- **Disabled states**: Always explain why via tooltip +- **Multi-step forms**: Progress indicator (Tabs or Breadcrumbs), save intermediate state + +### 5.4 Page Layout Patterns + +**File:** `guidelines/page-layouts.md` +**Skill:** `/page-layout` — Generates consistent page structures + +**Contents:** + +- **Standard page anatomy**: Page header (breadcrumb + title + actions) → Filters → Content → Pagination +- **Table page pattern**: Header with title + Create button, filter bar, data table, pagination +- **Detail page pattern**: Breadcrumb back, entity header with status badge, tabbed content sections +- **Settings page pattern**: Sidebar navigation (Tabs vertical), content area, save actions sticky footer +- **Dashboard page pattern**: KPI cards row, charts grid, recent activity table +- **Empty page pattern**: Illustration + explanation + CTA +- **Spacing rhythm**: Consistent gaps between sections (use Stack with specific gap values) +- **Content width**: Max-width constraints for readability + +### 5.5 Status & State Patterns + +**File:** `guidelines/states.md` +**Skill:** `/states` — Ensures consistent state handling + +**Contents:** + +- **Loading states**: Skeleton for known layouts, Loader spinner for unknown content, "Loading [entity]..." text +- **Empty states**: Illustration + explanation + primary action CTA +- **Error states**: Alert component (color=destructive), retry action when applicable +- **Success states**: Toast for transient, Alert for persistent in context +- **Partial states**: Skeleton for loading sections within loaded pages +- **Disabled vs readonly**: Disabled = can't interact (grayed out), Readonly = can view but not edit (normal appearance) +- **Selection states**: Checkbox for multi-select, Radio for single-select, highlight row/card on selection + +### 5.6 Navigation Patterns + +**File:** `guidelines/navigation.md` + +**Contents:** + +- **Breadcrumbs**: Always show on non-root pages, last item is current page (not clickable) +- **Tabs**: For same-page content switching, not for navigation between pages +- **Sidebar navigation**: For settings and configuration pages +- **Back button**: Use breadcrumbs, not a standalone back button +- **Deep linking**: All tab states and filter states should be URL-addressable + +### 5.7 Accessibility Guidelines + +**File:** `guidelines/accessibility.md` +**Skill:** `/a11y-check` — Validates accessibility of generated interfaces + +**Contents:** + +- **Color contrast**: All text meets WCAG 2.1 AA (4.5:1 for normal text, 3:1 for large) +- **Keyboard navigation**: All interactive elements focusable, logical tab order, visible focus rings +- **Screen reader**: All images have alt text, all icons have labels, dynamic content uses aria-live +- **Motion**: Respect `prefers-reduced-motion`, provide alternatives for animations +- **Form accessibility**: Labels linked to inputs, error messages linked via aria-describedby +- **Modal accessibility**: Focus trap, return focus on close, ESC to dismiss + +### 5.8 Iconography Guidelines + +**File:** `guidelines/iconography.md` + +**Contents:** + +- **When to use icons**: Paired with text for scannability, standalone only for universally understood actions (close, search, settings) +- **Icon + text rules**: Icon before text for actions, icon after text for external links +- **Icon sizing**: Match text size (use icon token sizes), maintain optical balance +- **Icon color**: Inherit text color (`currentColor`), use semantic colors for status icons +- **Custom icons**: Contribution process, SVG requirements, naming convention + +--- + +## 6. Tier 3: Platform Knowledge + +### 6.1 Product Context File + +**File:** `guidelines/wallarm-platform.md` + +This file gives AI tools context about what Wallarm is and what interfaces they're building. Without this, an LLM will generate generic interfaces instead of Wallarm-appropriate ones. + +**Contents:** + +- **What Wallarm is**: API security platform (WAF, API discovery, vulnerability detection) +- **User personas**: Security engineer, DevOps, CTO, compliance officer +- **Domain terminology**: Rules, triggers, attacks, incidents, endpoints, API specifications, vulnerabilities +- **Common entities**: Rules (IP rules, behavioral rules, virtual patches), Attacks (hits, payloads, sources), APIs (endpoints, schemas, parameters) +- **Navigation structure**: Main sections of the platform (Dashboard, Attacks, Rules, API Discovery, Settings) +- **Data density**: Security products are data-heavy — tables with many columns, dashboards with charts, detail pages with logs + +### 6.2 Existing UI Patterns Library + +**File:** `guidelines/existing-patterns.md` + +Document actual patterns used in the Wallarm Console today, so AI generates code consistent with the existing product. + +**Contents:** + +- **Attack list page**: How attacks are displayed (table with columns, filters, detail drawer) +- **Rule creation flow**: How rules are created (multi-step dialog, field dependencies) +- **Dashboard layout**: KPI cards, chart arrangement, time range selector +- **Settings organization**: How settings pages are structured +- **Common filter combinations**: What filter types are used together + +--- + +## 7. Skills & Agents Roadmap + +### 7.1 New Skills to Create + +| # | Skill Name | Trigger | What It Does | +|---|-----------|---------|--------------| +| **0** | **`/describe-component`** | **"describe Button", "create llm.md", "document component"** | **THE CORNERSTONE SKILL. Researches Figma + Storybook + interviews human → generates standardized .llm.md file. See Section 4.5 for full detail.** | +| 1 | `/ux-copy` | "write UI text", "error message", "empty state text" | Generates UI text following Wallarm voice & tone guidelines. Reads `guidelines/ux-copywriting.md` | +| 2 | `/data-format` | "format dates", "display numbers", "show status" | Enforces data display consistency. Reads `guidelines/data-display.md` | +| 3 | `/form-pattern` | "create a form", "add form fields", "validation" | Builds consistent forms with proper field ordering, validation, layout. Reads `guidelines/forms.md` | +| 4 | `/page-layout` | "create a page", "build a view", "new page" | Generates page layouts following Wallarm patterns. Reads `guidelines/page-layouts.md` | +| 5 | `/a11y-check` | "check accessibility", "a11y", "screen reader" | Validates and fixes accessibility issues. Reads `guidelines/accessibility.md` | +| 6 | `/states` | "loading state", "empty state", "error state" | Generates proper loading/empty/error/success state implementations | +| 7 | `/component-picker` | "which component should I use", "what's the best component for" | Interactive component selection wizard using decision trees | +| 8 | `/ui-review` | "review this interface", "check this UI", "is this correct" | Reviews generated UI code against all guidelines and suggests improvements | +| 9 | `/prototype` | "quick prototype", "wireframe", "mockup" | Rapid prototyping skill optimized for PMs — creates working HTML prototypes | +| 10 | `/icon-picker` | "which icon", "find icon for", "icon for action" | Searches icon library with semantic understanding | + +### 7.2 Enhanced Existing Agents + +**Design System Agent** — Enhance with: +- Auto-read of relevant `.llm.md` file when working on a component +- Composition validation (checks sub-component usage against composition rules) +- Accessibility checklist enforcement from metadata + +**Component Architect Agent** — Enhance with: +- Read guidelines for forms, layouts, states when designing new components +- Auto-suggest related components and composition patterns +- Decision tree for pattern selection based on use case + +### 7.3 New Agents + +| Agent | Role | When Triggered | +|-------|------|----------------| +| **UI Consistency Agent** | Reviews generated code against all guidelines | After any UI code generation | +| **UX Copy Agent** | Reviews and corrects all UI text in generated code | When generating UI with text content | +| **Platform Context Agent** | Injects Wallarm-specific context into component choices | When building Wallarm product features | + +--- + +## 8. MCP Server Enhancements + +### 8.1 New Tools + +| Tool | Input | Output | Purpose | +|------|-------|--------|---------| +| `suggest_component` | `{ useCase: string }` | Ranked component suggestions | Help LLMs pick the right component | +| `get_pattern` | `{ pattern: string }` | Full pattern with code | Provide common UI patterns | +| `get_guideline` | `{ topic: string }` | Relevant guideline content | Access to above-component guidelines | +| `validate_composition` | `{ component: string, children: string[] }` | Validation result | Check if component composition is correct | +| `get_related_components` | `{ component: string }` | Related components with context | Discover companion components | + +### 8.2 Enhanced Existing Tools + +**`get_component`** — Now returns: +- "When to Use" / "When NOT to Use" sections +- Composition requirements +- Accessibility profile +- Related components +- Do's and Don'ts + +**`search_component`** — Now searches: +- Tags and categories +- "When to use" descriptions +- Related components + +### 8.3 New Resources + +| Resource URI | Content | +|-------------|---------| +| `ds://guidelines/{topic}` | UX copywriting, data display, forms, etc. | +| `ds://patterns/{name}` | Common UI patterns with code | +| `ds://platform` | Wallarm product context | +| `ds://decision-tree/{use-case}` | Component selection guidance | + +--- + +## 9. .cursorrules / Editor Integration + +**Deliverable:** `.cursorrules` file in repo root for Cursor users, equivalent for Windsurf. + +**Contents:** + +``` +You are building interfaces with the Wallarm Design System (@wallarm-org/design-system). + +Core rules: +- Always import from '@wallarm-org/design-system' or '@wallarm-org/design-system/{Component}' +- Use the MCP server (wallarm-ds) to look up components, props, and tokens before writing code +- Never use raw HTML elements when a design system component exists (e.g., use + + + +``` + +### Alert with Bottom Actions +Use when the alert is narrower than ~450px and top-right buttons would compress the text. AlertControls is placed *inside* AlertContent. +```tsx + + + + Destructive alert with actions + This requires your attention. + + + + + + +``` + +### Alert with Code Output +For error messages that include technical details. Embed a Code component inside AlertContent. +```tsx + + + + Syntax Error in Configuration + An error occurred while parsing the configuration file. +
+ + Error: Unexpected token at line 42, column 15 + +
+
+ +
+``` + +## Accessibility +- **ARIA:** Root element has `role="alert"` — screen readers announce it immediately +- **Close button:** Has `aria-label="close"` and a "Close" tooltip +- **Overflow text:** When title or description is truncated via `lineClamp`, a tooltip shows the full text on hover + +## Content Guidelines + +Text inside alerts follows the same principles as Toast (WIP — will be governed by UX copywriting skill later): + +- **Title is a statement** — clear, short, sentence case. Best case: up to 3 words. +- **No trailing punctuation** in titles +- **No articles** — avoid "the", "an", "a" where possible +- **No assertive politeness** — avoid "please", "note", "successfully" +- **Description explains** — accompanies the title with additional context. Free-form but short and concise. +- **Button labels respond to the title** — e.g., title "Event was shared with you" → button "Open event" + +## Do's and Don'ts + +| Do | Don't | +|----|-------| +| Match color to semantic intent of the message | Pick a color for visual aesthetics | +| Set alert width to match its container (form, dialog, section) | Use a fixed arbitrary width that doesn't align with the layout | +| Use AlertIcon with every alert — icons are fixed per color | Override the icon for semantic color variants | +| Place actions bottom when alert is narrow, top-right when wide | Always default to one placement without considering layout | +| Keep most alerts permanent (non-dismissable) | Add AlertClose to every alert by default | +| Write titles as short statements in sentence case | Use title case, trailing punctuation, or "please"/"note" | + +## Related Components + +| Component | Relationship | When to prefer | +|-----------|-------------|----------------| +| Toast | Alternative | Transient feedback that auto-dismisses (success messages, quick confirmations) | +| Dialog | Alternative | Blocking messages that require a user decision before continuing | +| Field (error) | Alternative | Inline validation errors tied to a specific input field | +| Banner | Alternative | Page-level or system-wide announcements (not implemented yet) | +| Code | Companion | Embed inside AlertContent for technical error details | +| Button | Companion | Use inside AlertControls with `variant='secondary'` and `size='small'` | + +## Multiple Alerts + +When several alerts appear in the same section, stack them vertically with `gap-16` (16px) between them. Order by severity: destructive first, then warning, then info, then primary. + +## Platform Context + +In the Wallarm Console: +- **Delete confirmation dialogs** use `destructive` Alert inside Dialog to emphasize that the object cannot be restored +- **Object creation forms** use `warning` Alert on top of the form when there are post-creation limitations (e.g., "You won't be able to edit this rule after creation") +- **Object detail pages** use `info` Alert at the top of the page content area to show state information (e.g., "This attack was marked as false positive by @admin") +- **Success alerts are rare** — transient success feedback goes through Toast instead + +## Tags +alert, message, notification, inline-message, status, warning, error, info, success, feedback, persistent-message, compound