Skip to main content
Glama
README.md
[![npm version](https://img.shields.io/npm/v/ui-gateway.svg?style=flat-square)](https://www.npmjs.com/package/ui-gateway)
[![npm downloads](https://img.shields.io/npm/dm/ui-gateway.svg?style=flat-square)](https://www.npmjs.com/package/ui-gateway)
[![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](LICENSE)
[![Node 20+](https://img.shields.io/badge/node-%3E%3D20-green.svg?style=flat-square)](https://nodejs.org/)
[![ci](https://github.com/yuvraajnarula/uigateway/actions/workflows/ci.yml/badge.svg)](https://github.com/yuvraajnarula/uigateway/actions/workflows/ci.yml)

# UI Gateway

A library-agnostic, project-aware gateway that turns a design handoff into
**verified** UI component mappings. It fails closed: when it cannot answer
safely it returns a typed refusal that names what is missing.

- **12 adapters, one conformance suite.** shadcn/ui, MUI, Chakra UI v2 and v3, Mantine, Nuxt UI, unified Radix, Vue, Svelte, Angular, SolidJS, Bootstrap and Ant Design. Every adapter implements the same interface and passes the same suite.
- **Project-aware.** Detects framework, styling systems, installed UI libraries,
  local components and project skill files. Mode is `greenfield` or `existing`,
  detected and overridable.
- **Code-written scaffolds.** The selection stage may only pick from vetted
  candidate IDs. Imports, props, variants and composition come from the
  knowledge base. The gateway returns code; it never writes files.
- **Per-intent isolation.** One bad intent returns a typed per-intent error; the
  rest still map. `strict` is opt-in.
- **Protocol with ownership.** Leases, a hash-chained append-only event log,
  idempotency, and `RETURNED` as the only exit.

## Demo

![The Casa Verdé demo: hero, menu and reservation sections](site/demo.gif)

A restaurant landing page mapped end-to-end onto a real Next.js + shadcn app:
`npm run demo:restaurant` returns seven verified mappings with both acceptance
checks passing, and `node demo/restaurant/walkthrough.mjs` replays the narrated
run. See [demo/restaurant](./demo/restaurant/README.md).

## Quality

- **CI:** typecheck, build, tests, coverage thresholds, docs examples, evals and
  the end-to-end demo run on Linux, Windows and macOS; packed-install smoke tests
  run on Node 20/22/24. See `.github/workflows/ci.yml`.
- **Coverage:** `npm run test:coverage` enforces floors (statements/lines 78%,
  branches 74%, functions 76%); current coverage is ~79% statements.
- **Latency:** `npm run bench` reports handoff-to-result percentiles (p50/p90/p99).
- **Evals:** the pre-registered harness compares the gateway against a plain-agent
  baseline. The only committed model-backed sample (a 6-item CPU run, `gemma3:1b`)
  is directional, not a frontier result:

  | Arm | Hit rate | Compiles | Constraints | Mean wall |
  | --- | --- | --- | --- | --- |
  | gateway full skill | 66.7% (30.0–90.3) | 100% (51.0–100) | 100% | 5.6 s |
  | plain agent, no gateway | 0% | 16.7% | 83.3% | 24.3 s |

  Intervals are Wilson 95%. See `BENCHMARK.md` for method and reproduction.
  A key-backed frontier run at full stride is pending; `BENCHMARK.md` has the
  exact steps and a table to fill from the committed JSON.

## Installation

```bash
npm install ui-gateway
```

Then set up your target project with one command:

```bash
npx ui-gateway init --project /absolute/path/to/your/app
```

`init` detects Claude Code, Cursor, VS Code, OpenCode or a generic MCP client,
writes/merges the client config, copies the skill into `.ui-gateway/skill`, and
prints project detection plus any `needs_input` questions. To print a config
without writing anything:

```bash
npx ui-gateway mcp:config --project /absolute/path/to/your/app
npx ui-gateway mcp:config --project /absolute/path/to/your/app --client cursor
```

Clients without MCP can use the CLI equivalent:

```bash
npx ui-gateway init --project /absolute/path/to/your/app --print-skill
```

The gateway never writes to your project — it returns scaffolds, mappings and
typed refusals for you to apply. See [NON-GOALS.md](./NON-GOALS.md) for
deliberate limits.

## Quick start

```bash
npm install
npm run typecheck
npm test
npm run demo            # end-to-end: greenfield shadcn + existing MUI
npm run demo:restaurant # restaurant landing page end-to-end (see demo/restaurant)
npm run eval            # pre-registered eval harness (offline stand-in arms)
npm run eval:agent      # build -> validate -> submit contract over the golden set
npm run eval:claude     # real Claude three-arm run (requires ANTHROPIC_API_KEY)
npm run eval:groq       # OpenAI-compatible/Groq run (requires GROQ_API_KEY)
npm run eval:local      # real local Ollama benchmark + plain-agent arm
npm run eval:repos      # pinned external repos; add -- --pins-only to resolve commits
npm run site            # regenerate site/index.html from eval artifacts
npm run eval:site       # Playwright site eval over the dashboard fixture
npm run eval:page       # generated page shell: axe, keyboard, states, disclosure
npm run eval:page:real  # actual MUI/Chakra/Mantine scaffolds and themes
npm run calibration     # reliability curve -> docs/calibration.svg\nnpm run site            # generated open-caveats status page -> site/index.html
```

Node 20+ is required. The default in-memory event log has no native
dependencies. `--sqlite <file>` needs Node 22.5+ because it uses `node:sqlite`,
and fails with an explicit message on older Node.

## Agent skill

The agent-facing skill is [SKILL.md](./SKILL.md), with self-contained
references and examples:

| File | Purpose |
| --- | --- |
| `references/design-md.md` | Strict Design MD grammar and checklist. |
| `references/handoff.md` | Handoff fields, wireframe convention, hashing, idempotency. |
| `references/outcomes.md` | Outcome table, result fields, reporting, file-writing policy. |
| `references/errors.md` | Error codes and retry policy. |
| `references/patterns.md` | Page plan, dashboard pattern, required states and page checks. |
| `references/composition-apis.md` | Version-sensitive library APIs and token projection. |
| `references/tools.md` | Tool order, inputs, MCP resources and setup. |
| `examples/design-md.md` | Valid example Design MD. |
| `examples/handoff-input.json` | Builder input for regenerating the example handoff. |
| `examples/handoff.json` | Complete, hash-pinned example handoff. |

The skill expects the MCP server. Print a ready-to-paste config:

```bash
npx ui-gateway mcp:config --project /absolute/path/to/your/app
npx ui-gateway mcp:config --project /absolute/path/to/your/app --client opencode
```

The first form prints a generic `mcpServers` config; `--client` also accepts
`claude`, `cursor` and `vscode`. `--project` is the application the agent edits,
not this repository. `npx ui-gateway init` writes the config for you.

## MCP

The MCP server exposes 14 tools over stdio:

- `detect_project` — profile, provenance, confidence, `needs_input`.
- `describe_kb` — supported libraries, entries, `kb_version`.
- `hash_design_md` — normalized Design MD hash.
- `import_design_md` — read and validate a Design MD file from disk.
- `import_design_tokens` — convert DTCG JSON into Design MD tokens.
- `validate_design_md` — grammar, normalizations, policy, satisfiability.
- `derive_design_md` — infer a valid Design MD from the project's tokens.
- `build_handoff` — generates the wireframe, pins the profile/hash and returns a
  validation report.
- `validate_handoff` — the gateway's pre-flight checks plus a strict semantic
  gate, including Design MD compilation, schema version, KB freshness and
  satisfiability.
- `submit_handoff` — returns the result, `state` and `ownership_returned`,
  plus `page_plan`, `page`, `token_projection` and `warnings` when present.
- `map_ui` — two-call happy path: detect/derive, build, validate and submit.
- `verify_page` — read-only page check for anchors, ids, unused imports, basic
  a11y, the main landmark, duplicate display utilities and responsive
  breakpoint conflicts; can optionally compile the page and its related
  scaffolds in a throwaway TypeScript project.
- `get_handoff` — state, ownership, lease and result from the event log.
- `refusal_ledger` — repeated refusal reasons and suggested fixes.

<!-- TOOLS:START -->
| Tool | Purpose |
| --- | --- |
| `detect_project` | Detect the UI profile of a project: framework, styling, libraries, local components and project skill files. |
| `describe_kb` | List supported libraries, licenses, availability and component entries. |
| `hash_design_md` | Compute the Design MD sha256 after the gateway's deterministic normalization. |
| `import_design_md` | Read a Design MD file from the project filesystem, validate it against the strict grammar, and return its normalized content, hash and validation report. |
| `import_design_tokens` | Read a DTCG (Design Tokens Community Group) JSON file and convert its tokens into Design MD token entries. |
| `validate_design_md` | Validate a Design MD against the strict grammar and the project profile. |
| `build_handoff` | Build a complete, hash-pinned handoff from a Design MD and intents. |
| `validate_handoff` | Run the gateway's pre-flight checks plus a strict semantic gate: schema, supported schema version, design hash, Design MD compilation, semantics, satisfiability, profile hash, KB freshness and adapter support. |
| `submit_handoff` | Submit a validated handoff and receive verified component mappings. |
| `verify_page` | Read-only page check: syntax, broken or dead anchors, missing page_plan region ids, duplicate ids, unused imports, missing img alt, unlabeled links/buttons and the main landmark. |
| `derive_design_md` | Infer a strict Design MD from the project's CSS variables, Tailwind config, DTCG token files and an existing DESIGN.md. |
| `map_ui` | Two-call happy path. |
| `refusal_ledger` | Summarize repeated refusals from the event log (missing information, ambiguity, unsatisfiable constraints) and suggest fixes. |
| `get_handoff` | Read a handoff's state, ownership and result from the event log. |
<!-- TOOLS:END -->

It also serves the references and examples as MCP resources
(`ui-gateway://reference/handoff`, `ui-gateway://example/handoff`, and so on).
The integration test builds, validates, submits and reads a handoff over
JSON-RPC.

Agent order:

```text
detect_project -> describe_kb -> validate_design_md -> build_handoff
  -> validate_handoff -> submit_handoff -> (write files) -> verify_page
  -> get_handoff
```

Do not skip `build_handoff`; it generates the wireframe and hash that the
gateway expects.

### Discovery

`server.json` publishes the server to the official MCP Registry as
`io.github.yuvraajnarula/uigateway`, and `mcpName` in `package.json` proves npm
ownership; `smithery.yaml` declares Smithery's TypeScript runtime with
`target: "local"`, served by the SDK entry in
`packages/transports/src/smithery.ts`. The npm listing resolves to
`npx ui-gateway mcp` (add `--project <app>` to point it at an app).
`npm run check:mcpb` builds and schema-validates an MCPB bundle; publishing it
is a browser sign-in at <https://smithery.ai/new> (Smithery has been part of
Arcade since August 2026 and stopped its own API, accounts and API keys on
31 October 2026, deprecating its CLI and SDKs), while `npm run publish:mcpb`
still drives the documented release API for a workspace that holds a key.
[docs/smithery-listing.md](./docs/smithery-listing.md) holds the listing copy,
the tool card and the post-publish checklist.
See [docs/mcp-registry.md](./docs/mcp-registry.md) for the submission flow and
the GitHub Marketplace steps for `action.yml`.

## CLI

```bash
npm run cli -- init evals/fixtures/projects/existing-mui --dry-run
npm run cli -- detect evals/fixtures/projects/existing-mui
npm run cli -- kb --library shadcn
npm run cli -- validate examples/handoff.json
npm run cli -- validate-design examples/design-md.md
npm run cli -- build-handoff examples/handoff-input.json --out examples/handoff.json
npm run cli -- submit examples/handoff.json --project evals/fixtures/projects/greenfield-react
npm run cli -- submit examples/handoff.json --out .tmp/response.json   # echoes "wrote <path>" on stderr
npm run cli -- preview .tmp/response.json --out .tmp/preview.html
npm run cli -- submit examples/handoff.json --sqlite .tmp/events.sqlite
npm run cli -- status <handoff_id> --sqlite .tmp/events.sqlite
npm run cli -- label evals/fixtures/labels.jsonl
```

`submit` prints the full `SubmitResponse` JSON; `--out` writes it to a file and
confirms the path on stderr, so stdout stays JSON. Exit codes follow the outcome
(0 `COMPLETED`, 1 `REJECTED`, 3 `NEEDS_INPUT`, …) — see `references/outcomes.md`.
`build-handoff` reads a `HandoffInput` JSON file and writes or prints the complete
handoff. `preview` renders a result as standalone, dependency-free HTML.
`check` prints JSON by default; add `--text` for the one-line-per-finding list.
`kb-freshness <library> --current <version>` fetches the npm registry and any
`--docs <url>` pages and prints drift proposals with citations and a 0–1
confidence score; it never edits the KB or opens a PR. Documentation URLs must
be on the library's official host (from its `source_url`, plus any
`--official <host>`), and non-official URLs are rejected rather than cited.

Every KB library records the version line its entries were verified against
(`describe_kb` → `libraries[].library_version`, entries and mappings carry the
same field). Generated scaffolds start with `// library@line`, so a scaffold is
never silently reused across majors.

## HTTP transport

The gateway can also run as an HTTP server exposing the same tools:

```bash
npm run cli -- http --port 3456 --project /absolute/path/to/app
```

Endpoints:

- `GET /health` — health check.
- `GET /tools` — list available tools.
- `POST /tools/call` — call a tool with `{ "name", "arguments" }`.
- `POST /handoff` — submit a handoff directly.
- `POST /validate` — validate a handoff with the full pre-flight report.
- `POST /validate-design` — validate a Design MD.
- `GET /project?path=.` — detect a project profile.
- `GET /kb?library=shadcn` — describe the knowledge base.

## Publishing

UI Gateway is published to npm as `ui-gateway`. The internal `@uigw/*` workspace
packages are kept private; consumers install the root package which bundles the
full gateway, CLI, MCP server, and HTTP server.

```bash
npm install ui-gateway
```

Then configure the MCP server for your target project:

```bash
npx ui-gateway mcp:config --project /absolute/path/to/your/app
```

This prints a ready-to-paste MCP client config. The gateway never writes to your
project — it returns scaffolds, mappings, and typed refusals for you to apply.

### Releasing

Versioning and the changelog are managed by
[Changesets](https://github.com/changesets/changesets). Maintainers merge the
automated **Version Packages** pull request, then push a `vX.Y.Z` tag; the
`release` workflow publishes to npm with provenance and uploads the SBOM. See
`CONTRIBUTING.md`.

## Maintainers

- [@yuvraajnarula](https://github.com/yuvraajnarula)

Maintainers are the default owners in [`.github/CODEOWNERS`](./.github/CODEOWNERS).
Want to help maintain the project? See the "Becoming a maintainer" section in
[`CONTRIBUTING.md`](./CONTRIBUTING.md).

The repo is MIT licensed. See `LICENSE` for details.

## How a handoff flows

```text
CREATED -> VALIDATED -> ACCEPTED -> IN_PROGRESS -> terminal -> RETURNED
```

Terminal states are `COMPLETED`, `PARTIAL`, `NEEDS_INPUT`, `AMBIGUOUS`,
`FAILED`, `EXPIRED`, `REJECTED`, `CANCELLED`. Illegal transitions throw.

Before any matching, the gateway checks:

1. schema (Zod) and `schema_version` support;
2. integrity (`design_md_hash`, pinned `profile_hash`, handoff content hash for
   idempotency);
3. shared semantic validators (duplicate ids, impossible nesting, cross-field
   contradictions);
4. the Design MD compiler and its satisfiability check against the project
   profile;
5. adapter capability for the detected framework;
6. KB freshness against the pinned `kb_version`.

In page mode the composed page is a multi-file scaffold. `Page.tsx` imports the
intent components from `page_import_prefix` (explicit, or auto-inferred from the
project's `tsconfig.json` `paths`: first `@/*`, then `~/`, then the first
non-relative alias), the required-states return type and helper live in a
separate `page-state.ts`, scoped CSS lives in `page.css` and imports via
`import "./page.css";` (no inline `<style>`), and a typed `PageProviders`
wrapper is emitted as `PageProviders.tsx` when the plan has providers. Token
projections emit per-library theme files (`theme.mui.ts`, `theme.chakra.ts`,
`theme.mantine.ts`) plus a per-library merge helper (`theme.mui.merge.ts`,
`theme.chakra.merge.ts`, `theme.mantine.merge.ts`); the merge helper is the
recommended entry point when the project already has a theme.

Then each intent is filtered, ranked, selected, scaffolded, verified and scored
independently. Verification runs the schema check, KB existence, import roots,
prop/variant AST checks, lint rules compiled from the Design MD, two-way coverage
and adapter-specific import rules. Failed candidates are retried up to twice,
then the intent fails with typed detail.

The result and its `RETURNED` event are written in one transaction. A crash
mid-task leaves an expiring lease; `recoverExpired()` returns ownership with
`EXPIRED`.

Error codes (retryable in brackets): `INVALID_HANDOFF`, `INTEGRITY_MISMATCH`
[retry], `CONFLICT`, `UNSATISFIABLE_CONSTRAINTS`, `NO_MATCH`, `KB_STALE`
[retry], `LEASE_EXPIRED` [retry], `LEASE_CONFLICT` [retry], `UNSUPPORTED`,
`INTERNAL`, `RESULT_REJECTED`.

## Packages

| Package | Responsibility |
| --- | --- |
| `@uigw/protocol` | Zod schemas, state machine, leases, hash-chained event log (memory + SQLite), semantic validators, hashing |
| `@uigw/design-md` | strict Design MD parser, normalizer, constraint compiler, satisfiability |
| `@uigw/profile` | project detector with provenance/confidence, local component derivation, skill capture, conflicts |
| `@uigw/kb` | three-layer knowledge base, provenance tiers, ingest quarantine, staleness, drift |
| `@uigw/adapters` | adapter interface, shadcn, MUI, Chakra v2/v3, Mantine, Nuxt UI, Radix, Vue, Svelte, Angular, SolidJS, Bootstrap, Ant Design, local-components adapter, conformance suite |
| `@uigw/matcher` | filter, rank, closed-ID selection, code-written scaffolds |
| `@uigw/verifier` | TSX AST checks, design lint, coverage, optional tsc sandbox |
| `@uigw/gateway` | wiring, leases, retries, acceptance, validation report, result assembly |
| `@uigw/orchestrator` | handoff builder and caller-side re-verification |
| `@uigw/transports` | CLI, MCP server, HTTP server, shared tools, resources |
| `evals` | golden set, mutation harness, metrics, baseline comparison, agent contract eval |

Dependencies point one way. `protocol` and `design-md` know nothing about the
LLM.

## Writing a handoff

An agent should use the MCP tools:

1. `detect_project`
2. `describe_kb`
3. `validate_design_md` until `ok: true`
4. `build_handoff`
5. `validate_handoff` until `ok: true` and `profile_needs_input` is empty
6. `submit_handoff`

`build_handoff` returns the complete handoff and a validation report. Do not
hand-write the hash or wireframe.

From TypeScript, the same builder is available directly:

```ts
import { buildHandoff } from "@uigw/orchestrator";
import { createGateway } from "@uigw/gateway";

const gateway = createGateway({ projectDir: "." });
// buildHandoff defaults to all_intents_mapped + scaffolds_compile;
// the MCP build_handoff tool defaults to all_intents_mapped only.
const handoff = buildHandoff({
  design_md: myDesignMd, // see references/design-md.md
  project: { dir: ".", policy: { new_dependencies: "ask" } },
  intents: [
    {
      id: "submit",
      intent_type: "action",
      description: "Submit the order",
      elements: ["submit-button"],
      attributes: { interaction: "click" },
    },
    {
      id: "orders",
      intent_type: "data_display",
      description: "Recent orders table",
      elements: ["orders-table"],
    },
  ],
});

const response = await gateway.submit(handoff);
// `ok` is true only for COMPLETED; every other outcome still carries a result.
console.log(
  response.outcome,
  response.result?.intents.map((intent) => intent.mappings[0]?.component_id),
);
```

## Evaluations

- `npm run eval` runs the golden set and the no-retrieval/plain stand-in arms.
- `npm run eval:agent` runs the exact agent path (`build_handoff` ->
  `validate_handoff` -> `submit_handoff`) and writes
  `evals/out/agent-report.json`. It fails if any item cannot be built, validated
  or submitted, or if the positive mapped rate drops below 70%. It also reports
  rounds (`tool_calls_total`, `tool_calls_per_item`, `max_tool_calls`) so a
  contract change that adds retries is visible.
- `npm run eval:claude` runs the real Claude arms (`ANTHROPIC_API_KEY`).
- `npm run eval:groq` runs the OpenAI-compatible/Groq arms (`GROQ_API_KEY`).
- `npm run eval:local` runs the gateway and plain-agent arms against Ollama
  (`UIGW_LOCAL_MODEL`; results are local-model results, not frontier numbers).
- `npm run eval:repos -- --pins-only` resolves every external fixture commit
  with `git ls-remote`; `npm run eval:repos` shallow-clones and detects them.
- `npm run site` writes `site/index.html`, a generated status page for the open
  caveats, benchmark numbers, adapters and external pins.
- `npm run eval:site` serves the dashboard fixture and drives it in installed
  Chrome with `playwright-core`; it checks anchors, search/empty state, row
  detail, mobile navigation and console errors. It is not part of `npm test`.
- `npm run eval:page` composes the page shell for every responsive mode,
  bundles it with stub intent components, and runs axe WCAG A/AA, landmark,
  anchor, keyboard, focus, required-state, disclosure, mobile-overflow and
  console checks in Chrome. It checks the shell, not the real library
  components. It is not part of `npm test`.
- `npm run eval:page:real` submits page-mode handoffs for the MUI, Chakra and
  Mantine fixtures, writes the actual generated scaffolds plus the projected
  native theme, bundles against the installed packages, and runs the same
  browser checks. It is not part of `npm test`.
- `--local-llm` supports Ollama; `--simulatedBehavior` supports deterministic
  stand-ins. See `docs/metrics.md`.
- For API-backed evals, copy `.env.example` to `.env` and fill in the key.

## Design decisions you will notice

- **No guessing.** A Design MD with an unknown section, key or unenforceable
  pattern is rejected rather than silently ignored.
- **Policy precedence.** Policy fields the Design MD sets explicitly win;
  otherwise the project context policy applies.
- **`new_dependencies`.** `forbid` removes catalog candidates, `ask` returns
  `NEEDS_INPUT` with a `dependency_changes` entry that has
  `requires_approval: true`, `allow` proceeds and records the change.
- **Skills are advisory.** Rules from `SKILL.md`/`AGENTS.md` may break ties
  between vetted candidates and are reported as conflicts; they never override a
  hard constraint.
- **Free text is data.** Intent descriptions, wireframe notes and project skill
  rules never reach an instruction position and never reach generated code.
- **Confidence is computed.** Retrieval score, top-two margin, first-pass
  verification and sample agreement; model self-reports are ignored.

## Known limitations

- The default selector is deterministic (`rules`). Real model evaluation is
  available through Claude, an OpenAI-compatible/Groq endpoint, or Ollama. The
  offline evals also include simulated behaviors; see `docs/metrics.md`.
- The `tsc` sandbox stubs library types. It catches syntax and local type
  errors; prop correctness comes from the KB AST check.
- Local component derivation handles exported function and arrow components,
  class components, and re-exported library components.
- v1 supports React-family frameworks (shadcn, MUI, Chakra v2/v3, Mantine,
  unified Radix), Vue, Svelte, Angular, SolidJS, Bootstrap and Ant Design.
- The Chakra adapter is version-aware: v2 projects receive flat exports, v3
  projects receive dotted namespaces (`Table.Root`, `Dialog.Root`). Nuxt UI and
  Radix output is a component sketch; Nuxt UI does not yet emit a compiled Vue
  SFC, and both adapters remain experimental until labeled eval data exists.
- The golden set meets the Phase 6 count gate (124 dev + 48 test) across five
  fixtures — greenfield, existing-shadcn, existing-MUI, existing-Chakra and
  existing-Mantine — so every shipping adapter has labeled positives. Its labels are
  author-labeled against the KB, not blind human labels, and there has been no
  15% relabel for self-agreement; calibration is therefore still open. A blind
  subset and pipeline exist; self-agreement measurement is available via
  `--blindOnly --nSamples`.
- SQLite leases coordinate multiple processes competing for the same handoff.
  Full distributed orchestration is still post-v1; the in-memory event log is
  single-process.
- The MCP and HTTP transports have integration tests covering handshake, tools,
  resources, build, validate, submit, status and the HTTP endpoints. A live
  third-party client demo is still environment-dependent.
- The repository is published to npm as `ui-gateway`. Distribute the skill by
  copying `SKILL.md`, `references/` and `examples/`; generate MCP config with
  `npm run mcp:config`.