# Plan: Visual Spec Builder (GUI)

**Status**: Draft
**Author**: Prism Core Team
**Created**: 2026-02-06
**Updated**: 2026-02-06

## Overview

Build a web-based visual editor for creating and editing Prism specifications. Instead of hand-writing YAML/Python specs, users drag and drop models, draw relationships, configure fields with dropdowns, and export a valid spec — dramatically lowering the barrier to entry. This transforms Prism from a developer-only CLI tool into something accessible to technical product managers, designers, and junior developers.

## Goals

- Web-based visual editor at `builder.prism.dev` (also runnable locally via `prism builder`)
- Drag-and-drop model canvas with visual relationship lines (ERD-style)
- Field editor with type dropdowns, validation rules, and relationship pickers
- Real-time spec preview (live YAML/Python output as you build)
- One-click export to `specs/models.py` or `prism.yaml`
- Import existing specs for visual editing
- Live validation with instant error feedback
- Sharable spec URLs for collaboration

## Non-Goals

- Full IDE replacement (not trying to replace VS Code / Cursor)
- Code editing within the builder (spec only, not generated code)
- Deployment or generation from the builder (export spec → use CLI to generate)
- Mobile-responsive editing (desktop-first)

## Design

### User Interface

#### 1. Model Canvas (Main Area)

- Infinite canvas with zoom/pan (like Figma, Excalidraw)
- Models rendered as cards showing name + field list
- Relationships drawn as lines between model cards (arrow direction indicates type)
- Color-coded relationship lines: blue (many_to_one), green (many_to_many), gray (one_to_one)
- Double-click model card to open field editor
- Right-click context menu: duplicate, delete, add relationship

#### 2. Model Card

```
┌──────────────────────────┐
│  📦 Order                │  ← model name (editable)
├──────────────────────────┤
│  id          int (PK)    │
│  customer    str          │
│  total       Decimal      │
│  status      enum ▼       │
│  created_at  datetime     │
│  + Add Field              │  ← click to add
├──────────────────────────┤
│  → User (many_to_one)    │  ← relationships section
│  ↔ Tag (many_to_many)    │
└──────────────────────────┘
```

#### 3. Field Editor Panel (Right Sidebar)

When a field is selected:
- Name input
- Type dropdown (str, int, float, bool, datetime, date, text, email, url, enum, json, Decimal)
- Validation rules (max_length, min/max, regex pattern)
- Toggles: required, unique, indexed, primary_key
- Default value input
- Enum value editor (for enum type)
- Relationship configuration (target model, type, cascade)

#### 4. Global Settings Panel

- Project name, description
- Auth configuration (enable/disable, provider)
- API exposure (REST, GraphQL, MCP toggles)
- Docker, CI/CD, deploy toggles
- i18n settings, realtime settings (if plugins available)

#### 5. Spec Preview Panel (Bottom/Right)

Live-updating code view showing the generated spec:

```python
# Live preview updates as you edit
from prisme.spec import StackSpec, ModelSpec, FieldSpec

spec = StackSpec(
    name="my-app",
    models=[
        ModelSpec(
            name="Order",
            fields=[
                FieldSpec(name="customer", type="str", max_length=100),
                FieldSpec(name="total", type="Decimal"),
                ...
            ]
        )
    ]
)
```

### Technical Approach

#### 1. Architecture

```
┌─────────────────────────────────────────────┐
│           Visual Spec Builder               │
│                                             │
│  React + TypeScript + React Flow            │
│  ┌─────────┐  ┌──────────┐  ┌───────────┐  │
│  │ Canvas  │  │  Editor  │  │  Preview  │  │
│  │(ReactFlow)│ │ (Forms) │  │  (Monaco) │  │
│  └─────────┘  └──────────┘  └───────────┘  │
│                     │                       │
│              ┌──────┴──────┐                │
│              │  Spec Store │ (Zustand)      │
│              └──────┬──────┘                │
│                     │                       │
│              ┌──────┴──────┐                │
│              │  Validator  │ (WASM/API)     │
│              └──────┬──────┘                │
│                     │                       │
│              ┌──────┴──────┐                │
│              │  Exporter   │                │
│              └─────────────┘                │
└─────────────────────────────────────────────┘
```

- **React Flow** for the node-based canvas (MIT licensed, battle-tested)
- **Zustand** for spec state management
- **Monaco Editor** for spec preview with syntax highlighting
- **Zod** for client-side spec validation

#### 2. Spec State Model

```typescript
interface SpecState {
  project: ProjectConfig
  models: ModelNode[]
  relationships: RelationshipEdge[]
  auth: AuthConfig | null
  plugins: PluginConfig[]
}

interface ModelNode {
  id: string
  name: string
  position: { x: number; y: number }
  fields: FieldConfig[]
}

interface RelationshipEdge {
  id: string
  source: string        // model id
  target: string        // model id
  type: "many_to_one" | "many_to_many" | "one_to_one"
  fieldName: string
  cascade: boolean
}
```

#### 3. Import / Export

**Export formats**:
- `specs/models.py` (Pydantic spec — primary)
- `prism.yaml` (YAML spec — alternative)
- JSON (for sharing/embedding)
- PNG/SVG (diagram export)

**Import**:
- Parse existing `specs/models.py` or `prism.yaml`
- Auto-layout models on canvas using dagre/elk algorithm
- Preserve all field configurations and relationships

#### 4. Validation Engine

Real-time validation as user edits:
- Model name conflicts
- Missing required fields
- Invalid relationship targets
- Circular dependency detection
- Field type compatibility checks

Validation runs client-side with a JSON schema derived from Prism's Pydantic spec models.

#### 5. Local Mode (`prism builder`)

```bash
# Start the visual builder locally
prism builder
# → Opens http://localhost:3333 with your project's spec loaded

# Start with a blank canvas
prism builder --new

# Start with a specific spec file
prism builder --spec specs/models.py
```

The CLI serves the builder as a static SPA and provides API endpoints for:
- Reading/writing the local spec file
- Running validation against the full Prism spec parser
- Triggering generation after export

### API Changes

- No changes to the Prism CLI API — the builder is a standalone tool
- Optional: `POST /api/validate` endpoint in local mode for server-side validation

### Database Changes

- None — the builder is a pure client-side application

## Implementation Steps

1. **React Flow canvas** — Model cards as nodes, relationships as edges, drag/drop
2. **Field editor** — Right sidebar with type selection, validation rules, toggles
3. **Spec state store** — Zustand store with undo/redo history
4. **Spec serializer** — Convert visual state → `specs/models.py` / YAML
5. **Spec parser** — Import existing specs → visual state with auto-layout
6. **Validation engine** — Real-time client-side validation with error markers
7. **Preview panel** — Monaco editor with live spec output
8. **Global settings** — Auth, API, Docker, deploy configuration panels
9. **Local CLI** — `prism builder` command serving the SPA
10. **Hosted version** — Deploy to `builder.prism.dev` with share URLs
11. **Tests** — Canvas interactions, serialization round-trips, validation rules

## Testing Strategy

- **Unit tests**: Serializer (state → spec → state round-trip), validation rules
- **Component tests**: Canvas interactions (add/remove/connect models), field editor
- **E2E tests**: Full flow — create spec visually → export → generate → verify output
- **Snapshot tests**: Exported spec format stability

## Rollout Plan

1. Local-only `prism builder` with model canvas + field editor + export
2. Import existing specs + validation
3. Global settings panels (auth, API, etc.)
4. Hosted version at `builder.prism.dev`
5. Sharable spec URLs + collaboration features

## Complexity & Effort

**Effort Estimate**: 8-10 weeks (1 senior frontend developer + 1 backend developer)
**Complexity**: HIGH — new standalone application, complex UI interactions

## Dependencies

- Stable spec model API (current spec models are stable)
- None of the other roadmap features are required

## Risk Assessment

**High Risks**:
- Canvas performance with 50+ models (mitigated: React Flow virtualization, lazy rendering)
- Spec serialization fidelity — visual → code → visual must be lossless (mitigated: round-trip tests)
- Feature parity with YAML/Python spec — builder must support everything the text format does

**Medium Risks**:
- Maintenance burden of a separate frontend application
- User expectations may exceed what a visual tool can express

**Adoption Risk**: MEDIUM — strong value for new users, power users may prefer text editing.

## Open Questions

- Should the builder support real-time collaboration (multiple cursors, like Figma)?
- Should we embed the builder in VS Code as a webview extension?
- Should the builder support undo/redo with full history persistence?
- How should advanced spec features (custom validators, computed fields) be represented visually?
