## Figma -> Component Generation

Skill set lives in the marketplace plugins  -  `ai-ios-toolkit` (iOS/SwiftUI) and `ai-android-toolkit` (Android/Compose). Activated when the task contains a Figma URL and target files are `.swift` (iOS) or `.kt` (Android).

### MUST: Figma access - 3-tier fallback chain (BLOCKING, pipeline-wide)

When any task references a Figma frame (URL, node ID, or free-text "from the design"), the pipeline MUST resolve a Figma ground-truth artefact via the chain below before any UI line is written, every phase that consumes or verifies the reference (Phase 0 intake, Phase 1 analysis, Phase 2 planning, Phase 3 dev, Phase 4 review, Phase 5 manual test, Phase 7 channels). Skipping the chain has cost multiple rebuild rounds across projects.

The three tiers run in strict priority order. A tier is "available" when its required credentials / inputs are present AND a probe call succeeds. Lower tiers are tried only when the higher tier is unreachable.

#### Tier 1 - Figma MCP (preferred)

Tools:
- `mcp__claude_ai_Figma__get_design_context(fileKey, nodeId)`: primary; returns code + screenshot + `CodeConnectSnippet` blocks naming the exact target component.
- `mcp__claude_ai_Figma__get_screenshot(fileKey, nodeId)`: pixel render for visual diff against the implementation.
- `mcp__claude_ai_Figma__get_metadata(fileKey, nodeId)`: when the frame structure is unknown.

Auth failure is NOT a skip path. Run `mcp__claude_ai_Figma__authenticate` + `mcp__claude_ai_Figma__complete_authentication` and retry once. If the retry also fails, do NOT silently fall through to Tier 2  -  surface an `AskUserQuestion` (`question` + `description` in `outputLanguage`; `label` + `header` English):
- **Recreate the MCP token** - the `figma_mcp` credential is dead; re-onboard it via the Token Save Flow (`setup.md`), then retry Tier 1.
- **Continue with Figma PAT** - proceed to Tier 2 (REST) for this run.

Only on the explicit "Continue with Figma PAT" choice (or when no `figma_mcp` token is mapped at all) does the chain move to Tier 2.

The MCP token itself resolves through `prefs.global.keychainMapping.figma_mcp` (relevant for MCP server config bootstrap; the `mcp__claude_ai_Figma__*` tool calls themselves run through Anthropic-managed MCP auth, but the token MUST be onboarded so the auth flow has something to bind to).

#### Tier 2 - Figma Personal Access Token via REST API (fallback)

Token retrieval goes through `~/.claude/lib/credential-store.sh get <logical-key>` where `<logical-key>` is read from `prefs.global.keychainMapping.figma` (or whichever per-user logical name the mapping resolves to). The literal Keychain service name is NEVER embedded in any synced file under `~/.claude/commands/` or `~/.copilot/skills/`; see the Synced Command Hygiene rule.

Endpoints:
- Design context (frame metadata + structure):
  `GET https://api.figma.com/v1/files/{fileKey}/nodes?ids={nodeId}` with header `X-Figma-Token: $TOKEN`.
- Screenshot render:
  `GET https://api.figma.com/v1/images/{fileKey}?ids={nodeId}&format=png&scale=2` with the same header. The response is a signed URL valid for 30 days; download it locally before the URL expires.

If the REST call returns 401 / 403 (the PAT is expired or revoked), do NOT silently fall through to Tier 3  -  run the Expired-token decision (`refs/keychain.md` Rule 1) for `figma`: **Regenerate** / **Use a different token** / **Skip and continue**. Only on the explicit "Skip and continue" choice (or when no `figma` is mapped) does the chain move to Tier 3.

Tier 2 does NOT return a Code Connect snippet (the REST API has no equivalent). When operating on Tier 2, the canonical-component decision falls back to the repo's `*.figma.swift` / `*.figma.kt` mappings (search by `fileKey` + `nodeId`); if none match, record an Open Question for the design team and pick the closest existing primitive WITH user confirmation.

#### Tier 3 - User-attached screenshot (last resort)

When the user supplies screenshots inline in chat or via task attachments and Tiers 1 + 2 are both unreachable, treat the screenshot as the visual ground truth and document the limitation. Tier 3 produces a degraded evidence record: `codeConnectSnippets` is empty, the canonical-component decision is "tier-3 best-fit pending design review", and the Phase 4 reviewer flag is set to `review_blocking` until a human signs off on the component choice.

#### Halt condition

If all three tiers fail (no MCP auth AND no REST token AND no screenshot), HALT the run and ask the user how to proceed. Never substitute primitives, never guess from Confluence prose, never derive layout from a text description.

#### URL parsing

`figma.com/design/{fileKey}/...?node-id={id}`: convert `-` to `:` in node IDs. Branch URL `figma.com/design/{fileKey}/branch/{branchKey}/...` uses `branchKey` as the effective `fileKey`.

#### Code Connect snippet rules (Tier 1 + Tier 2 when the repo mapping fills the gap)

- The `CodeConnectSnippet` block (Tier 1) or the matching `*.figma.swift` / `*.figma.kt` row (Tier 2) names the exact target component the design team mapped. Use that component name verbatim.
- Sound-alike alternatives are forbidden. Picking a similarly-named component because it appears more flexible introduces visual drift on avatar icons, field grouping (one rounded box vs two), separators, character counters, button heights, header styles, inline-error layout.
- If the chosen component is missing a modifier (placeholder, counter toggle, height override, error-state binding), add the modifier to the component in its `+Modifiers.swift` (or platform equivalent). Do not fork, do not silently render the wrong visual, do not extract a custom wrapper inside the consumer domain.

Architecture notes must cite the exact node IDs (Tier 1 or Tier 2) or attach the user-provided screenshot reference (Tier 3) for every UI atom row. Visual feedback that arose from skipping the chain ("expandable broken", "placeholder missing", "counter showing", "wrong avatar icon") is treated as a blocker review finding, not a normal iteration.

#### Generic checklist before writing any UI line

1. Establish the tier in use and persist it as `state.figmaAccess.tier` (1, 2, or 3). Tier 3 forces a review-blocking flag.
2. Call the tier-appropriate fetcher for every frame variant (default, filled, error, indicator-on, RTL, etc.).
3. Resolve the canonical component name: Tier 1 from `CodeConnectSnippet`, Tier 2 from repo `*.figma.swift` / `*.figma.kt`, Tier 3 from explicit user confirmation.
4. Compare screenshot to mental render: avatar icon, indicator chip placement, field grouping, separator vs gap, placeholder copy, counter visibility, button height, header style, inline error colour and location.
5. Map design tokens (CSS vars on Tier 1, screenshot inspection on Tier 3) onto project token namespaces (`Spacing*`, `Color*`, `Radius*`, `Typography*`); never invent numeric or hex values.
6. Re-run the chain when the spec changes or the user reports visual drift; do not assume the prior fetch is current.

## MUST: No MCP outside analysis phase (BLOCKING, pipeline-wide)

The 3-tier fallback chain above governs Figma access in `/multi-agent:analysis` only. Once the analysis document is rendered (Phase 1 of the analysis subcommand), the analysis doc + repo Code Connect mappings (`*.figma.swift` / `*.figma.kt`) are the sole design source for every downstream phase. Calling `mcp__claude_ai_Figma__*` tools, hitting `api.figma.com`, or fetching a `figma.com/design/...` URL during Phase 2, 3, 4, 5, 6, or 7 is a violation.

### Phase access matrix

| Phase | Sub-command examples | Figma MCP allowed | Figma REST allowed | Reason |
|---|---|---|---|---|
| Analysis Phase 1 | `/multi-agent:analysis` Phase 1 fetch | yes | yes (Tier 2 fallback) | Single source of design ground truth |
| Plan (Phase 2) | `/multi-agent`, `/multi-agent:local`, `/multi-agent:autopilot`, `/multi-agent:local-autopilot` | no | no | Plan reads analysis doc Section 14 + Section 6 |
| Dev (Phase 3) | every mode that runs Phase 3 (8 modes total) | no | no | Reads analysis doc + Code Connect mapping |
| Review (Phase 4) | `/multi-agent:review`, every full-pipeline mode | no | no | Reviewer cites analysis doc Section 21 References |
| Test (Phase 5) | `/multi-agent:test`, `/multi-agent:manual-test`, every full mode | no | no | Variant list comes from analysis Section 13.6 + 15.2 |
| Commit (Phase 6) | every mode | no | no | PR body links to analysis doc URL, no design fetch |
| Report (Phase 7) | `/multi-agent:channels`, every full mode | no | no | Channels embed analysis doc, no design fetch |

### Halt condition

If Phase 2+ encounters a need to look at the design (missing variant, ambiguous padding, unknown copy), the run halts and the user is instructed to re-run `/multi-agent:analysis` to regenerate the doc with the missing piece. Never silently call MCP as a fallback.

### Why

Re-fetching Figma in dev phases:
- Burns MCP tokens (slow + costly)
- Duplicates the work analysis already did
- Splits the design source of truth (analysis doc says X, MCP says Y if Figma edited mid-run)
- Defeats the analysis -> dev contract: the analysis doc is supposed to be self-contained

### Verification

The pipeline ships a smoke gate `pipeline/scripts/smoke-no-mcp-in-dev-phases.sh` that reads `state.telemetry.mcpCalls[]`. If any entry has `phase >= 2`, the gate fails. CI runs this gate after every run as a regression check.

Memory: [[mcp-only-in-analysis]]

### Phase Order (platform-agnostic)

```
0-Init -> 1-Gather -> 2A-TestingIDs -> 2B-Localization -> 2C-Accessibility -> 2D-Analytics
-> 3-TokenMapping -> 4A-Configuration -> 4B-View -> 4C-Docs -> 4D-Preview -> 4E-Modifiers
-> 5A-Structural -> 5B-Snapshot -> 5C-Unit -> 6-CodeConnect -> 7-Wiki -> 8-Cleanup
```

### Configuration

Per-project config at `~/.claude/projects/{slug}/figma-config.json`.
Schema: `pipeline/schemas/figma-project-config.schema.json`.
Template: `preferences-template.json` → `_figmaConfigTemplate` section.

### Variable System

All skill files use `{variableName}` placeholders  -  no hardcoded project values.
Variables resolved from `figma-config.json` by the orchestrator at Phase 0.
Placeholder catalog ships alongside each skill's `SKILL.md`.

### Target File Structure

| File                      | Content                             |
| ------------------------- | ----------------------------------- |
| {Name}Configuration.swift | Pure value type: all properties     |
| {Name}View.swift          | SwiftUI view, renders Configuration |
| {Name}+Modifiers.swift    | Fluent modifier API chain           |
| {Name}.figma.swift        | Code Connect registration           |
| FIGMA.md                  | Variant matrix, usage examples      |

### Component Architecture

```swift
struct ButtonConfiguration {
    var title: String = ""
    var style: ButtonStyle = .primary
    var isEnabled: Bool = true
}

struct ButtonView: View {
    let configuration: ButtonConfiguration
    var body: some View { ... }
}

extension ButtonView {
    func title(_ value: String) -> ButtonView {
        var c = configuration; c.title = value; return ButtonView(configuration: c)
    }
}
```

### Mandatory Token Rules

- No magic numbers: `padding: 16` -> `.Spacing.spacing16`
- No raw hex colors: `Color(hex: "#E31837")` -> `Color.Primary.primary`
- No raw `.font()` -> `.typographyStyle(.body1)`
- Token hierarchy: Spacing > Size > Radius > BorderWidth > Color > Typography

### Pre-Commit Checklist

- [ ] No magic numbers/raw colors/fonts
- [ ] Accessibility IDs from UITestingIdentifiers
- [ ] Localization keys defined
- [ ] 3-layer tests: structural + snapshot + unit
- [ ] Code Connect .figma.swift written
- [ ] Preview shows all meaningful variants
- [ ] FIGMA.md contains variant matrix

### SubPhase Integration (multi-agent Phase 3)

When Figma pipeline is active (`figmaConfigPath` set in project preferences),
multi-agent Phase 3 (DEV) dispatches Figma sub-phases instead of standard TDD:

```
Phase 3.0: figma-to-swift-ui-start    → Branch, assign, registry
Phase 3.1: figma-to-swiftui           → Full 8-phase implementation
Phase 3.2: figma-commit               → 14-item review + commit + PR
Phase 3.3: figma-iteration-commit     → Batch iteration commit (if iterating)
```

### Abstraction Layers

| Layer | Provider Options | Config |
|-------|-----------------|--------|
| Board | `github-projects-v2`, `github-labels-only`, `none` | `board.provider` |
| Registry | `swift-cli`, `json-file`, `none` | `registry.type` |
| Confluence | enabled/disabled | `confluence.enabled` |
| Wiki | enabled/disabled | `wiki.enabled` |
| Figma API | MCP / REST fallback | `figma.mcpEnabled` |

Provider interfaces are defined inline in the plugin skill sets  -  see the `ai-ios-toolkit` and `ai-android-toolkit` marketplace plugins.

### Optional Features (graceful skip when disabled)

| Feature | Config | Skip Behavior |
|---------|--------|---------------|
| Registry CLI | `registry.enabled` | Manual component name/path input |
| Projects V2 Board | `board.enabled` | No board column updates |
| Wiki | `wiki.enabled` | Phase 7 wiki skipped |
| Confluence | `confluence.enabled` | Phase 7a confluence skipped |
| Figma MCP | `figma.mcpEnabled` | REST API fallback |

### 14-Item Review Checklist

1. File completeness
2. No magic numbers (design tokens required)
3. Configuration purity
4. +Modifiers correctness
5. Accessibility identifiers
6. Analytics tracking
7. Testing identifier pipeline
8. Preview quality (LTR + RTL)
9. Code Connect
10. View implementation quality
11. FIGMA.md documentation
12. Cleanup (artifact cleanup)
13. Build verification (xcodebuild)
14. Test verification (ViewInspector + Snapshot)

### Command Catalog (31 commands)

**Core Pipeline:**

| Command | What It Does |
|---------|-------------|
| `/figma-to-swiftui <url>` | Full 8-phase pipeline |
| `/figma-to-swift-ui-start #N` | Start from issue: branch, assign |
| `/figma-to-swift-ui-implement <url>` | Phases 0-4 only (implementation) |
| `/figma-to-swift-ui-test <url>` | Phase 5 only (tests) |
| `/figma-to-swift-ui-wiki <Name>` | Phase 7 only (wiki docs) |
| `/figma-to-swift-ui-code-connect <url>` | Phase 6 only (Code Connect) |
| `/figma-to-swift-ui-confluence-sync` | Sync wiki → Confluence |
| `/figma-to-swift-ui-status-update` | Refresh Confluence dashboard |

**Issue & Board:**

| Command | What It Does |
|---------|-------------|
| `/figma-issue open <url>` | Create GitHub Issue + optional Jira |
| `/figma-review <Name>` | Interactive review (approve/bug) |
| `/figma-validate <url>` | Pre-implementation validation |

**Commit & PR:**

| Command | What It Does |
|---------|-------------|
| `/figma-commit <Name>` | 14-item review + commit + PR |
| `/figma-iteration-commit <Name>` | Commit to iteration/develop + PR |

**Iteration & Batch:**

| Command | What It Does |
|---------|-------------|
| `/figma-iterate` | Auto loop: pick → implement → commit |
| `/figma-cli-iterate` | Full CLI iterate (all phases) |
| `/figma-cli-lean-iterate` | Lean iterate (skip test+wiki) |
| `/figma-cli-iterate-mend` | Re-implement discarded components |
| `/figma-cli-skip` | Mark component as skipped |
| `/figma-skip` | Skip + update Confluence |

**Bugfix:**

| Command | What It Does |
|---------|-------------|
| `/figma-fix` | Apply targeted bug fixes |
| `/figma-mend` | Re-implement from scratch |

**Setup & Utility:**

| Command | What It Does |
|---------|-------------|
| `/figma-setup` | Environment setup wizard |
| `/figma-utility` | Figma data fetch (screenshots, metadata) |
| `/figma-remote-mcp-auth` | Figma MCP OAuth flow |
| `/figma-ui-patterns` | UI pattern library index |
| `/figma-price-integration` | Price protocol adoption guide |

**Performance (batch production):**

| Command | What It Does |
|---------|-------------|
| `/performance-start #N` | Start component with perf tracking |
| `/performance-swiftui` | Perf-optimized pipeline |
| `/performance-tour` | Batch produce multiple components |
| `/performance-review-next` | Interactive batch review |
| `/performance-iteration-commit-all` | Batch validate + push all |
