# codedesign

Terminal design agent — a conversational REPL that turns natural-language design briefs into Figma work, enforced by your own design system.

```
$ npm i -g @wz927/codedesign@alpha
$ codedesign
```

> **Status:** `1.0.0-alpha.31` — early preview, feature-complete for the product loop (PRD → DS → plan → Figma → critique). See `ROADMAP.md` for the full milestone plan.

---

## What's in this alpha

- **Layered system prompt** — 11 ordered slots (bootstrap / brief / design-system / skill / craft / research / critique / summary / interaction). Skills rebuild the prompt in place.
- **Craft rules** — 11 vendored `craft/*.md` files (typography, color, accessibility, state-coverage, form-validation, anti-ai-slop, laws-of-ux, …). Every role gets them by default.
- **`craft_lint`** — deterministic anti-slop scanner (indigo-default, emoji-as-icon, invented metrics, filler copy, external placeholders). No LLM round trip.
- **Skills (8)** — `pitch-deck-figma`, `mobile-screens-figma`, `dashboard-figma`, `landing-page-figma`, `email-template-figma`, `docs-site-figma`, `form-system-figma`, `onboarding-flow-figma`.
- **Design systems** — 5 deterministic "schools" (`editorial-monocle` / `modern-minimal` / `warm-soft` / `tech-utility` / `brutalist-experimental`) each writing a 9-section `DESIGN.md` + flat `ds.json`. Plus `ds import <figma-url>` (REST distill → 6-role palette + font stacks, Variables API + named Styles priors + sampling fallback) and `ds pull <slug>` (vendor from `nexu-io/open-design`).
- **Figma write path** — `figma_execute` passes arbitrary Plugin API JS through the Figma Desktop Bridge plugin (`figma-console-mcp` v1.23.0, MIT).
- **Vision** — `image_understand` + per-DS `cases/` library, `list_cases` tool. Requires a vision-capable endpoint (`deepseek_vision_model`).
- **Web search** — `web_search` tool (Tavily default) + research layer activated when an API key is present. Sources numbered [1..N] with citation contract.
- **Critique loop** — `/critique` runs a 5-panelist (Designer / Critic / Brand / A11y / Copy) round loop until all score ≥ 3 with no new issues.
- **Session** — autosave to `~/.codedesign/sessions/<id>.json`, `--resume` list + resume, `/compact` summariser, opt-in `--auto`.
- **Local file tools** — `read_file`, `list_dir` for PRD / brand-spec ingestion.
- **CLI subcommands** — `codedesign ds list|show|init|import|pull|edit`, `codedesign auth show|set|remove|path`.

---

## Install

```bash
npm i -g @wz927/codedesign@alpha
codedesign              # first run prompts for your API key
codedesign --version
```

Requires Node.js 20+.

On first run you'll be asked for a DeepSeek (or any OpenAI-compatible) API key. It's saved to `~/.codedesign/auth.toml` with `chmod 600`.

## Configuration

`~/.codedesign/auth.toml`:

```toml
deepseek_api_key      = "sk-..."                       # required
deepseek_base_url     = "https://api.deepseek.com"     # default
deepseek_model        = "deepseek-chat"                # default
deepseek_vision_model = "deepseek-vl2"                 # optional — enables image_understand
figma_token           = "figd_..."                     # optional — enables figma_execute + ds import
tavily_api_key        = "tvly-..."                     # optional — enables web_search
search_provider       = "tavily"                       # default when tavily_api_key is set
```

Manage credentials without editing the file by hand:

```bash
codedesign auth show
codedesign auth set figma_token figd_xxxxxxxxxxxx
codedesign auth remove tavily_api_key
codedesign auth path
```

Secrets are masked on display (`sk-1…cdef (48 chars)`).

### Case library (`~/.codedesign/cases/`)

Drop reference images into `~/.codedesign/cases/` and the agent will see them listed in its system prompt. It can then call `image_understand` with a `case_id` (the filename without extension) to pull a design digest from the vision model. Optional sidecar `<name>.json` files can add metadata:

```json
{
  "title": "Hero — split with image right",
  "description": "Left-aligned headline, right image, two CTAs",
  "tags": ["hero", "marketing"],
  "source": "https://example.com/inspiration"
}
```

## Design system

At any point you can have exactly one active DS, described by two files:

- `~/.codedesign/ds.json` — flat token list (`ds_query` index)
- `~/.codedesign/design-systems/<id>/DESIGN.md` — authoritative 9-section spec (visual theme / palette / typography / components / spacing / shadows / motion / tokens / guidelines)

Three ways to produce one:

```bash
# 1. Pick a built-in visual direction (5 schools, deterministic)
codedesign ds list
codedesign ds init editorial-monocle --brand Acme

# 2. Distill an existing Figma file
codedesign ds import https://www.figma.com/design/ABC/File    # requires figma_token
# Previews palette+fonts with provenance (variables / styles / sampling), asks y/N.

# 3. Vendor an opendesign DESIGN.md (palette from DESIGN.md, ds.json hand-authored)
codedesign ds pull stripe

# Edit the authoritative DESIGN.md in $EDITOR:
codedesign ds edit
codedesign ds show
```

`ds_query` fuzzy-searches tokens/components. The agent calls it before proposing any color / spacing / component name so suggestions stay inside your system.

## Tools

Run `/tools` in the REPL to see what's active. Headline capabilities:

- **`ds_query`** — fuzzy token/component lookup against the bound DS.
- **`list_directions` / `pick_direction`** — the 5-school picker; `pick_direction` writes ds.json + DESIGN.md and reloads the session.
- **`craft_lint`** — deterministic P0 craft rule scan (copy blob or Figma frame JSON).
- **`figma_distill_ds`** — same engine as `ds import`, callable mid-conversation.
- **`figma_execute`** — Figma Plugin API passthrough (see setup below).
- **`image_understand` / `list_cases`** — vision model digest of case library images or ad-hoc URLs/paths.
- **`web_search`** — Tavily-backed search with numbered sources.
- **`read_file` / `list_dir`** — local PRD / reference ingestion.

### `figma_execute` — Figma Plugin API passthrough

Executes arbitrary Figma Plugin API JavaScript inside your running Figma Desktop session. This is the primary write-to-canvas capability.

**One-time setup:**

1. Install Figma Desktop: <https://www.figma.com/downloads>
2. Generate a Figma Personal Access Token: Figma → Settings → Security → Personal access tokens → Generate new token
3. `codedesign auth set figma_token figd_...`
4. Install the Desktop Bridge Plugin in Figma:
   - The plugin files are vendored at [`../figma-desktop-bridge/`](../figma-desktop-bridge/) (from `figma-console-mcp` v1.23.0, MIT).
   - In Figma Desktop: open any design file → Plugins → Development → **Import plugin from manifest** → select `figma-desktop-bridge/manifest.json`.
5. Before each session, run the plugin: **Plugins → Development → Figma Desktop Bridge**. Wait for "MCP ready" (green dot). Keep the window open.
6. Start codedesign.

Without these, `figma_execute` returns a structured error and the agent falls back to text-only advice.

Full setup walkthrough with troubleshooting: [`docs/figma-setup.md`](docs/figma-setup.md).

## REPL commands

| command | effect |
|---|---|
| (any text) | send to the agent |
| `/help` | list commands |
| `/tools` | list active tools and their schemas |
| `/ds` | print the currently bound DS (path, entry count) |
| `/skills` | list installed skills under `./skills/` |
| `/skill <slug>` | activate a skill — rebuilds the system prompt in place |
| `/skill none` | deactivate the current skill |
| `/critique` | run the 5-panelist critique loop over the last assistant turn |
| `/sessions` | list saved sessions (newest first) |
| `/resume <id>` | show how to resume a specific session |
| `/compact` | compact older turns into a summary (keeps last 4 user turns verbatim) |
| `/compact --auto` | auto-compact silently once history exceeds 40 messages |
| `/compact --off` | disable auto-compact |
| `/clear` | clear on-screen log (conversation history preserved) |
| `/exit` / `/quit` | quit |
| `Ctrl+C` | quit |

## Sessions

Every REPL conversation autosaves to `~/.codedesign/sessions/<id>.json` after each turn (atomic writes — no half-written files). Session ids are timestamp-sortable (`YYYYMMDD-HHMMSS-<rand>`).

```bash
codedesign --resume                         # list saved sessions
codedesign --resume 20260511-142305-a3f1    # pick one up
```

## License

MIT — see `LICENSE`. Vendored `figma-console-mcp` bridge plugin is MIT; see `NOTICE`.

---

## More docs

- [`docs/figma-setup.md`](docs/figma-setup.md) — full Figma Desktop + PAT walkthrough
- [`docs/e2e-checklist.md`](docs/e2e-checklist.md) — end-to-end manual acceptance checklist
- [`ROADMAP.md`](ROADMAP.md) — milestone plan
