# ASK — Figma Library Setup Guide

This is the operational manual for running Figma as the **single source of truth** for the ASK design system. It assumes you've already imported `tokens-studio.json` (see `IMPORT.md`). This file covers everything that happens *after* the tokens are in: file structure, component construction, naming, publishing, and the sync workflow with code.

---

## 1. File structure

Don't put everything in one Figma file. Split into **three files**, all in one team / project called **"ASK · Design System"**:

```
🎨 ASK · Design System (project)
├── 📄 01 — Foundations
│   └── Tokens, type ramp, color palette, voice & tone, iconography, logo
├── 📄 02 — Components
│   └── Primitives, feedback, overlays, navigation, data, forms, agentic AI
└── 📄 03 — Patterns
    └── Environments (chat / notebook / vertical), compliance patterns (A–D), composed flows
```

The **Patterns** file is load-bearing for ASK — it's where the three environments and the four mandatory compliance patterns live as reusable instances. Product designers compose from there, never reinventing.

Why three files?
- **Performance** — one giant file slows Figma to a crawl past ~500 components.
- **Permissions** — designers might edit Patterns daily, but Foundations should be locked except during version bumps.
- **Publishing scope** — each file publishes its own library; product files can subscribe to all three.

Your **product / marketing** files live in a separate project (`Ask · Product` or per-feature projects) and consume these three as libraries.

---

## 2. Page layout inside each file

### 📄 01 — Foundations

```
✶ Cover           — branded title page (logo, version, last updated)
✶ Tokens          — Tokens Studio plugin lives here
✶ Color           — every color variable as a labelled swatch grid (brand + neutral + state)
✶ Typography      — text styles ramp + usage examples
✶ Voice & tone    — the three attributes with copy examples (mirrors brand sheet)
✶ Iconography     — Lucide icon set, sized 16/20/24
✶ Logo            — wordmark + mark variants (linked from /logo SVGs)
✶ Spacing & radii — visual reference for the scale
✶ Motion          — duration + easing curves with animated demos
✶ Elevation       — z-index scale, dropdown / dialog / toast stacking
✶ Changelog       — every published change
```

### 📄 02 — Components

One **section** per category, one **page** per category if it gets big:

```
✶ Cover
✶ Primitives     — Button, Input, Select, Checkbox, Radio, Switch, Slider, Textarea
✶ Feedback       — Badge, Alert, Toast, Tooltip, Progress, Skeleton, Empty
✶ Overlays       — Dialog, Sheet, Popover, Dropdown, Command
✶ Navigation     — Top nav, Side nav, Tabs, Breadcrumbs, Pagination
✶ Data display   — Table, Card, List item, Avatar, Accordion, Code block
✶ Forms          — Field, validation states, multi-step
✶ Agentic AI     — Chat message, Agent status, Tool-call card, Citation chip, Streaming
✶ App shell      — Page header, Page templates
```

### 📄 03 — Patterns

Load-bearing for ASK. Some entries are reusable instances, some are full compositional examples:

```
✶ Cover
✶ Environments — LOAD-BEARING
   ├─ env/chat       — General Chat chrome (CHAT badge)
   ├─ env/notebook   — Notebook chrome (Knowledge Pod badge, split-screen)
   └─ env/vertical   — Vertical App chrome (App badge, stepper)
✶ Compliance — LOAD-BEARING, MANDATORY
   ├─ compliance/citation       — Pattern A: inline tag + source pane
   ├─ compliance/hitl           — Pattern B: slide-to-approve + multi-checkbox confirm
   ├─ compliance/guardrail      — Pattern C: active + block tones
   └─ compliance/rbac           — Pattern D: omit (do) / gray out (don't)
✶ Chat & agent runs    — full chat surface with all message types
✶ Dashboard            — agent fleet overview
✶ Empty + error states — every screen's zero / error / loading variant
✶ Forms                — sign-in, settings, agent config
✶ Onboarding           — first-run flow
```

> **Compliance and Environments are not optional.** Any product file that surfaces agent output without `compliance/citation`, or any external write without `compliance/hitl`, must be rejected at design review.

---

## 3. Component construction — the rules

These rules are what make a library actually usable. Break them and engineers will copy values instead of consume components.

### 3.1 Always use Auto Layout

Every component, every variant, every state. Hand-positioned rectangles break the moment text changes.

### 3.2 Bind every value to a token

No raw hex, no raw px. If a value isn't a token yet, **add the token** and bind. The few exceptions:
- Glyph-level path positions inside icons
- Inner construction lines on diagrams

Right-click any property in the Figma inspector → **Apply variable**. If the variable doesn't exist, the value doesn't belong in the system.

### 3.3 Variants and properties

For every component, expose Figma Properties so consumers don't need to detach:

| Property | Type | Example |
|---|---|---|
| `variant` | Variant | primary / secondary / ghost / outline / destructive |
| `size`    | Variant | sm / md / lg |
| `state`   | Variant | default / hover / active / focused / disabled |
| `loading` | Boolean | swap label for spinner |
| `icon-leading` | Instance swap | optional Lucide icon |
| `icon-trailing` | Instance swap | optional Lucide icon |
| `label`   | Text | the button label |

Boolean properties to **show / hide** elements are essential — e.g. a Card has a Boolean `has-header`, `has-footer`. Don't make a variant for every combination; you'll end up with 64 button variants.

### 3.4 Nest, don't duplicate

A `<Field>` is composed of `<Label>` + `<Input>` + `<HelpText>` + `<ErrorText>`. Build each piece as its own component and nest them. When you change the Input, every Field updates automatically.

### 3.5 Slots via instance swap

For Card, Dialog, Sheet — use **instance swap** properties for `content`. Default to a placeholder text block; consumers swap in their own component. This is how you avoid spec'ing 30 variants of "Card with X inside".

---

## 4. Naming convention

Strict, slash-separated, lowercase. This is what shows in the Assets panel and what code generators use.

```
✓ button/primary
✓ button/primary/hover
✓ input/text/default
✓ field/text                       (composed)
✓ card/article/with-header
✓ dialog/confirm
✓ agentic/message/agent
✓ agentic/tool-call/web-search

✗ Button — Primary                 (no spaces, no dashes around concepts)
✗ ButtonPrimary                    (no PascalCase — Figma is slash-namespaced)
✗ button-primary                   (this becomes one variant, not a hierarchy)
```

The first segment is the **category**, second is the **component name**, then **variants**. Match this to the import path in code:

```ts
import { Button } from '@/components/ui/button';        // matches: button/*
import { ToolCall } from '@/components/agentic/tool-call'; // matches: agentic/tool-call/*
```

---

## 5. Publishing the library

### 5.1 First publish

1. In **Foundations**, hit the **Assets** panel → **Publish library** (button at top of Assets panel, or `Assets → Publish library` in the menu).
2. Figma will show every component / variable that will publish. Tick the description box and write a meaningful first-release note: "v1.0 — initial release: foundations".
3. Click **Publish**.
4. Repeat for **Components** and **Patterns**.

### 5.2 Consuming in a product file

1. Open your product file (e.g. `Ask · Product / Chat surface`).
2. **Assets** panel → **Libraries** icon (book) → enable all three Ask libraries.
3. Components and variables are now available in the Assets panel and via `Shift + I`.

### 5.3 Pushing updates

When you change a library component:
1. Save the file.
2. **Assets → Publish library** again. Figma shows the diff (added / changed / removed).
3. Write a changelog entry: what changed and why.
4. Click **Publish**.
5. In product files, designers will see a **"Updates available"** badge in the bottom-right and can **Review and Accept** updates.

Never publish silently — every changelog entry should map to a code PR.

---

## 6. The sync loop with code

This is the part that makes "single source of truth" real.

```
   ┌──────────────┐  Tokens Studio   ┌─────────────────────────┐
   │   FIGMA      │ ───── push ────▶ │ tokens-studio.json (PR) │
   │              │ ◀──── pull ───── │                         │
   └──────────────┘                  └─────────────────────────┘
                                                │
                                                ▼ Style Dictionary build
                                     ┌─────────────────────────┐
                                     │  globals.css (HSL vars) │
                                     │  tailwind.preset.ts     │
                                     │  storybook theme.ts     │
                                     └─────────────────────────┘
                                                │
                                                ▼
                                     ┌─────────────────────────┐
                                     │  shadcn components      │
                                     │  Storybook + Chromatic  │
                                     └─────────────────────────┘
```

### 6.1 Tokens flow (Figma → code)

1. Designer changes a token value in Figma via Tokens Studio.
2. Tokens Studio → **Push to GitHub** (set up once with a fine-scoped PAT).
3. Opens a PR against `packages/brand/figma/tokens-studio.json`.
4. Repo CI re-runs Style Dictionary, regenerates `globals.css` + `tailwind.preset.ts`.
5. PR review → merge.
6. Storybook redeploys. Chromatic catches any visual regressions.

### 6.2 Components flow (code ↔ Figma)

Components have **no automated sync** — they're built twice, once in Figma, once in shadcn. This is fine **if** you treat the docs (Storybook + this Figma library) as the source of truth and the production code mirrors them. The discipline: any new shadcn component that doesn't exist in Figma gets one added before the PR lands.

### 6.3 Setting up the GitHub sync (one-time)

1. Create a bot account or use a designer's account. Generate a [fine-scoped PAT](https://github.com/settings/tokens?type=beta) with **Contents: read & write** on `mirai-srl/project-ask`.
2. In Tokens Studio: gear icon → **Sync providers** → **Add new → GitHub**.
3. Fill in:
   - Personal access token: *paste*
   - Repository: `mirai-srl/project-ask`
   - Branch: `main`
   - File path: `packages/brand/figma/tokens-studio.json`
   - Commit message template: `chore(tokens): {{description}}`
   - Pull request: ✓ enabled (so changes go through review)
4. Save. Now Tokens Studio shows a **Push / Pull** button in the bottom bar.

> ⚠️ If your repo enforces branch protection on `main` (it should), GitHub sync will need a fine-grained PAT that can create branches and PRs, not just push to main.

---

## 7. Versioning the library

Treat the library like a package:

- **Patch** (1.0.x): bug fixes, copy tweaks. No designer action required in product files.
- **Minor** (1.x.0): new components, new tokens. Backward compatible. Designers should accept updates at their convenience.
- **Major** (x.0.0): renames, removals, breaking changes. Communicate before publishing. Ideally batch into a planned release.

Publish notes live in `Foundations → Changelog`. Mirror them in `packages/brand/CHANGELOG.md` so engineers see the same history.

---

## 8. Roles & permissions

On the Figma Pro plan, set these roles in the **ASK · Design System** project:

| Role | Foundations | Components | Patterns |
|---|---|---|---|
| Design system owner | **Edit** | Edit | Edit |
| Product designers   | View | View | Edit |
| Engineers           | View | View | View |
| Stakeholders        | View | View | View |

Foundations is locked because changes there ripple through everything downstream. Only the system owner pushes token changes via Tokens Studio.

---

## 9. Daily workflow cheatsheet

**Designer wants to use a token in a frame:**
- Don't pick a color. Use the variable picker (right side panel → click the colored square next to Fill).

**Designer wants to add a new color/token:**
- Don't add it via Figma's Variables panel directly. Add it in Tokens Studio's editor, then push.

**Designer wants to use a button:**
- Drag from Assets panel (`Shift + I`). Never detach the instance. Change the variant via the right panel.

**Designer needs a custom one-off:**
- Build it as a normal frame **inside the Patterns file**. If it gets used twice, promote it to a component in the Components file.

**Engineer wants to know what a Figma component maps to in code:**
- The component's description field (right panel in Figma) should always include `Code: @/components/ui/button` or equivalent. Add this to every component.

---

## 10. Common pitfalls

| Pitfall | Why it happens | Fix |
|---|---|---|
| Hex codes leak into frames | Designers paste colors from screenshots | Code review-style review for the Foundations file; enforce variable bindings in Components |
| Components drift from code | No one set up the sync | Use Tokens Studio GitHub sync for tokens; add a `Figma:` link to every shadcn component's story |
| 60-variant button explosion | Every state × size × icon position is a variant | Use Boolean properties + instance swaps for icons; only make variants for things with different layouts |
| Library file slow | Too many components in one file | Split by category once a file has >150 components |
| Tokens Studio "nothing happens" on import | `$comment` / `$schema` at top of JSON | Use the version shipped in this folder (already stripped) |

---

## Next steps for you

1. Create the **"ASK · Design System"** team / project in Figma.
2. Create the three files (Foundations / Components / Patterns).
3. Import `tokens-studio.json` into the Foundations file (see `IMPORT.md`).
4. Use `Ask Design System.html` as the visual reference while you build the Components and Patterns files. Every component spec'd in that doc has a 1:1 Figma counterpart — every `comp-foot` shows the Figma path (`button/primary`, `compliance/citation`, `env/notebook`, etc.).
5. Once Components is populated, publish the library and consume in a product file.
6. Set up the Tokens Studio GitHub sync **last** — once the library is stable enough that designers want to make changes.
