# SpecVerse Tooling: the `spv` CLI

Command reference for the SpecVerse CLI. Covers installation, the 10 top-level commands, manifests, and the publish ritual.

**See also:**
- [SPECVERSE-INTRO.md](SPECVERSE-INTRO.md) — philosophy and ecosystem overview
- [SPECVERSE-SPECIFYING.md](SPECVERSE-SPECIFYING.md) — writing the `.specly` files the CLI operates on
- [SPECVERSE-APP-DEMO.md](SPECVERSE-APP-DEMO.md) — interactive runtime interpreter (alternative to generating + running code)
- [SPECVERSE-REALIZING.md](SPECVERSE-REALIZING.md) — deep dive on `spv realize` (manifests, instance factories, L1/L2/L3)

---

## Contents

- [Installation](#installation)
- [`spv smoke`](#spv-smoke) — verify your install (60-90s)
- [`spv init`](#spv-init) — scaffold a new project
- [`spv validate`](#spv-validate) — parse + schema-validate a `.specly`
- [`spv validate-bundle`](#spv-validate-bundle) — validate an entity bundle (for engine extenders)
- [`spv infer`](#spv-infer) — expand minimal specs to full architecture
- [`spv realize`](#spv-realize) — generate code from spec + manifest
- [`spv gen`](#spv-gen) — diagrams, docs, UML
- [`spv dev`](#spv-dev) — development tools (format, watch, quick)
- [`spv cache`](#spv-cache) — inference cache management
- [`spv ai`](#spv-ai) — AI workflows (docs, suggest, template)
- [`spv skill install`](#spv-skill-install) — install the SpecVerse Claude skill
- [`spv session`](#spv-session) — persistent AI sessions
- [Manifests](#manifests) — the HOW (link to SPECVERSE-REALIZING for full depth)
- [Publishing](#publishing) — release ritual for `@specverse/*` packages

---

## Installation

```bash
npm install -g @specverse/self
spv smoke              # verify (60-90s)
spv init my-app        # scaffold your first project
```

Node 20+ required. The CLI is exposed as both `specverse` and `spv` (short alias). Examples throughout this doc use `spv`.

---

## `spv smoke`

Verifies that the toolchain works end-to-end — install, init, realize, boot, CRUD.

```bash
spv smoke                       # ~60-90s; no flags or args needed
```

Spins up a throwaway project from the default template, realizes it, starts a backend, hits a CRUD round-trip, and tears down. If it prints `New-user smoke test passed ✅` you're good. If it doesn't, the failing step + backend logs are printed in place.

A separate `npm run smoke:static` (from within the specverse-self repo) exercises the ReactAppStarter path end-to-end: generates the standalone frontend, builds with vite, verifies belongsTo FK round-trips.

**Full release gate:** `npm run smoke:all` runs engines unit tests + verify:tarball (runtime path) + verify:tarball:static (static path) + contract UI suite (35 Playwright tests) + all 4 templates through init → setup → boot → test:e2e.

---

## `spv init`

Scaffolds a new project from a template skeleton.

```bash
spv init <name>                             # uses 'default' template
spv init <name> --template <t>              # explicit template choice
spv init <name> --static                    # ReactAppStarter (standalone starter kit)
```

### Templates

| Template | What you get | Spec |
|---|---|---|
| `default` | Monorepo scaffold (backend + frontend) | Canonical **Category + Item** spec (shared with app-demo's Server Manager new-spec action) |
| `full-stack` | Same monorepo scaffold | Rich **User / Project / Task** demo (lifecycles, relationships, behaviors, events) |
| `backend-only` | Standalone Fastify + Prisma API | Category + Item spec (no UI generated) |
| `frontend-only` | Standalone React SPA | Category + Item spec (no backend; expects external API) |

```bash
spv init my-app                                # default
spv init my-app --template full-stack           # rich demo
spv init my-app --template backend-only         # API only
spv init my-app --template frontend-only        # SPA only
```

### `--static` flag

Orthogonal to `--template`. Pre-swaps the manifest so `spv realize` emits a **ReactAppStarter** frontend (fully standalone, editable source, no `@specverse/runtime` dep) instead of the default **ReactAppRuntime** (slim shell that loads views at runtime).

```bash
spv init my-app --static                        # default template, static output
spv init my-app --template full-stack --static  # rich demo, static output
```

Pick `ReactAppStarter` when you want to fork and customize the generated React. Pick `ReactAppRuntime` when you want a thin generated surface you can regenerate freely without clobbering edits.

### `init` vs `realize` — two different commands

- **`spv init <name> --template <t>`** copies a *skeleton* from `templates/<t>/` into a new directory. The skeleton contains specs, manifests, CLAUDE.md, package.json — but **no generated code**. It's a starting point.
- **`spv realize all ...`** (below) calls the engines to generate `generated/code/` fresh from the current skeleton's spec and manifest.

### After `init`

```bash
cd my-app
npm run setup          # validate + realize + install deps + setup db (one command)
npm run dev:backend    # terminal 1
npm run dev:frontend   # terminal 2
npm run test:e2e       # Playwright end-to-end (backend + frontend must be running)
```

The "Next steps" hint is template-aware — backend-only sees `npm run dev`, frontend-only sees `npm run dev` + `test:e2e`, full-stack sees `dev:backend` + `dev:frontend` + `test:e2e`.

### `npm run setup-variants` (in specverse-self)

For interactive testing of all `spv init` options simultaneously:

```bash
npm run setup-variants
```

Preps six side-by-side projects under `tests/variants/`:

| Variant | `spv init` invocation | Ports |
|---|---|---|
| v-default | *(no flags)* | BE 3010, FE 5180 |
| v-default-static | `--static` | BE 3011, FE 5181 |
| v-fullstack | `--template full-stack` | BE 3012, FE 5182 |
| v-fullstack-static | `--template full-stack --static` | BE 3013, FE 5183 |
| v-backend | `--template backend-only` | BE 3014 |
| v-frontend | `--template frontend-only` | FE 5184 → v-default's BE |

Each variant gets its own `.env` (unique ports) and `run-dev.sh` helper so you can boot all six simultaneously without port collisions. Output dir is gitignored — regenerate whenever.

---

## `spv validate`

Parse and schema-validate a `.specly` file.

```bash
spv validate specs/main.specly                  # basic validation
spv validate specs/main.specly --verbose        # detailed error output
spv validate specs/main.specly --verify         # run Quint formal verification (L3 guards)
```

**Pipeline:** YAML parse → pre-convention schema validation → convention processor expansion → post-convention schema validation → semantic validation (cross-entity checks) → result.

**With `--verify`:** runs the transpiled Quint guards against the spec. On the self-spec, raw shows 7/7 hold and inferred shows 14/14, with skipped guards filtered by missing state vars or fields. Quint guards are validate-time only — they verify the spec, not live runtime data.

Exit codes: `0` = valid, `1` = validation errors, `2` = schema errors.

---

## `spv validate-bundle`

Validate an entity bundle directory — the `schema/` + `conventions/` + `inference/` + `generators/` + `__examples__/` + `__tests__/` + `__behaviour__/` shape that powers the pluggable-bundle model. Used by engine extenders adding new entity types.

```bash
spv validate-bundle path/to/bundle           # human output
spv validate-bundle path/to/bundle --json    # machine-readable BundleReport
```

**Six facet checks** (output of `validateBundle` from `@specverse/engines/bundles`):
1. `catalog` — `__examples__/` + `__tests__/` + `__behaviour__/` enumerable + cross-referenced
2. `schema` — fragment compiles cleanly under Ajv2020 + draft-07
3. `examples` — each `.specly` parses, exercises the bundle's entity type (parsed AST has the X-section, OR `.example.yaml` `concepts:` declares X)
4. `tests` — bundle-local imports only (`from '../...'`)
5. `docs` — every `.specly` has a colocated `.md` with H1 + bundle-name mention
6. `behaviour` — `.qnt` files typecheck via `quint typecheck` (skipped if Quint not on PATH)

Exit codes: `0` = all facets pass, `1` = one or more facets failed or path invalid.

See `specverse-self/docs/guides/SPECVERSE-EXTENDING.md` for the full bundle authoring guide.

---

## `spv infer`

Expand a minimal spec into full architecture via 21 deterministic inference rules.

```bash
spv infer specs/main.specly -o specs/main-inferred.specly
spv infer specs/main.specly -o specs/main-inferred.specly --deployment --verbose
spv infer specs/main.specly --environment production
```

### What gets inferred

| Input | Inferred output |
|---|---|
| Model with attributes | Controller with full CURVED operations |
| Model with relationships | Service with cross-model operations |
| Model with lifecycle | Evolve operation + lifecycle events |
| Model with behaviors | Service operations matching behaviors |
| Any model | List + Detail + Form views |
| Controllers + storage | Deployment instances |

Write 5 models, get 5 controllers + 5 services + 15+ events + 10+ views + deployment topology. ~4× to 7.6× expansion ratio.

**Flags:**
- `-o <path>` — output path (default: `-inferred.specly` suffix)
- `--deployment` — include deployment inference
- `--environment <env>` — target environment (development, staging, production)
- `--verbose` — show rule-matching trace

---

## `spv realize`

Generate production code from `spec + manifest`. This is the main code-generation entry point.

```bash
spv realize all <spec> -o <output-dir> -m <manifest>
```

### Basic usage

```bash
# Generate the entire stack
spv realize all specs/main-inferred.specly -o generated/code -m manifests/implementation.yaml

# Generate only specific parts
spv realize all specs/main.specly --part schema      # Prisma schema only
spv realize all specs/main.specly --part services    # Services only
spv realize all specs/main.specly --part routes      # Routes only
spv realize all specs/main.specly --part all         # Everything (default)

# Filter by deployment
spv realize all specs/main.specly --deployment production

# Filter by specific instance
spv realize all specs/main.specly --deployment production --instance UserService
```

### What gets generated

A complete project tree — exact shape depends on the manifest. Typical output:

```
generated/code/
├── backend/
│   ├── src/
│   │   ├── main.ts              # Fastify server with auto-wired routes
│   │   ├── routes/              # Route handlers per model
│   │   ├── services/            # Business logic with L3 behaviors
│   │   ├── controllers/         # CURVED controllers
│   │   └── <Model>.guards.ts    # Per-model constraint guards — only if the model declares constraints:
│   ├── prisma/                  # Prisma schema + migrations
│   └── package.json
├── frontend/
│   ├── src/
│   │   ├── App.tsx              # App shell with navigation
│   │   ├── components/          # List/detail/form views per model
│   │   └── api/                 # Type-safe API client
│   └── package.json
├── cli/                         # If spec defines commands
└── tools/                       # MCP server, VSCode extension (if manifest includes tools factories)
```

The specific technologies — which server framework, which ORM, which frontend library — are determined by the **manifest**, not the spec or the engines. Change the manifest, get a different stack from the same spec. See [SPECVERSE-REALIZING.md](SPECVERSE-REALIZING.md) for the full deep-dive on how realize works, instance factories, and the L1/L2/L3 behavior generation.

---

## `spv gen`

Generate diagrams, documentation, and UML from a spec.

```bash
spv gen diagrams <spec>                         # Mermaid diagrams (12+ types)
spv gen docs <spec>                             # Markdown documentation
spv gen uml <spec>                              # UML diagrams
```

**Diagram types:** ER, class, lifecycle, event-flow-layered, deployment-topology, model-architecture, manifest, architecture-layered, capability-bindings, technology-stacks, and more.

```bash
# Generate a single diagram type
spv gen diagrams specs/main.specly --type er

# Generate specific diagrams by name
spv gen diagrams specs/main.specly --type event-flow-layered --output docs/diagrams/
```

The diagram plugin system is registry-based. Entity modules can declare their own diagram plugins, so new entity types automatically contribute diagram types.

---

## `spv dev`

Development tools for iterating on specs.

```bash
spv dev quick <spec>               # fast schema-only validation (no convention processing)
spv dev format <spec>              # format + normalize the spec YAML
spv dev format <spec> --write      # format in place
spv dev watch <spec>               # watch and re-validate on file change
```

`quick` skips convention expansion and deep schema validation — useful for rapid feedback while editing. Always run `spv validate` before committing.

---

## `spv cache`

Manage the import resolver cache (resolved `imports:` directives are cached for performance).

```bash
spv cache --stats                 # show cache size + entry count
spv cache --list                  # list cached items
spv cache --clear                 # clear cache
spv cache --prune                 # remove stale entries
```

---

## `spv ai`

AI-assisted workflows.

```bash
spv ai docs <spec>                # generate implementation prompts from the spec
spv ai suggest <spec>              # get improvement suggestions for the spec
spv ai template <op>              # get the prompt template for an operation
```

Templates available (six active workflows): `create` (NL requirements → minimal spec), `verify-create` (semantic self-review of a draft created spec), `analyse` (codebase → spec + manifest + deployments triple — reverse-engineering with structural prepass injecting deterministic facts), `verify-analyse` (semantic self-review of analysed spec against source), `behavior` (pure function bodies for unmatched behavior steps), `app-demo` (interactive spec creation for the runtime interpreter).

**Two-stage patterns** (shipped 2026-04-26): `create → verify-create` lifted the 8-case create corpus from 75% → 100%. `analyse → verify-analyse` does the same for analyse runs against real codebases.

**Example:**

```bash
# Get the template for the 'create' operation
spv ai template create

# Run end-to-end LLM-backed analyse on a real codebase, with two-stage verify
spv ai analyse <source-dir> --output runs/<label> --verify

# Run end-to-end LLM-backed create from natural-language requirements
spv ai create "guesthouse booking with rooms, guests, lifecycle pending->confirmed->checked_in->checked_out" --verify
```

The AI engine uses Vercel AI SDK as canonical plumbing with four modes selected by `SPECVERSE_AI_PROVIDER` (`claude-cli` | `anthropic` | `openai-compatible` | `stub`). Defaults: inside an MCP server → stub; `claude` binary detected → claude-cli (Max-subscription zero-cost); `ANTHROPIC_API_KEY` set → anthropic; else stub. Prompts live under `@specverse/assets/prompts/core/standard/default/` (mutable tip) with frozen `v10/` baseline alongside. See `docs/guides/SPECVERSE-AI.md` for full reference.

### `spv realize --estimate`

Cost / walltime projection before committing to a generation. Reports expected output broken down by realize layer:

- **L1** — Instance factory (templates, no LLM) — N files
- **L2** — Convention pattern matching (CURVED op bodies, default events, no LLM)
- **L3** — AI from steps (one LLM call per declared `steps:` entry across behaviors / actions / operations)

Reports expected wall time + cost on Max / Sonnet API / DeepSeek for L3. Useful for cost-aware planning on larger codebases — extrapolations on a 26-entity hand-written codebase came in at ~120 LLM calls, ~25 min Max, ~$2 Sonnet, ~$0.10 DeepSeek.

---

## `spv skill install`

Install the SpecVerse Claude skill — a folder of `SKILL.md` + `reference/{guide,schema,ai-guidance,minimal-example,cli-reference}` + `workflows/*.md` (one per canonical prompt YAML) — into a Claude skills directory. Once installed, Claude Code auto-loads the skill into every session, giving the LLM ambient context about SpecVerse without you having to paste it each time.

```bash
spv skill install --global              # ~/.claude/skills/specverse/  (recommended for Max users)
spv skill install --project             # <cwd>/.claude/skills/specverse/  (per-repo, committable)
spv skill install --target /path/to/dir # explicit destination
```

Default (no flags) installs to `<cwd>/.claude/skills/specverse/`.

When the skill is installed AND `SPECVERSE_AI_PROVIDER=claude-cli`, behaviour generation skips the `fullContext` block in the system prompt (the skill already covers it) — saves ~2K tokens per session init. See [SPECVERSE-AI.md](./SPECVERSE-AI.md) for skill interaction details.

---

## `spv session`

Persistent AI sessions — cache-aware, token-efficient.

```bash
spv session create --name "my-session"
spv session list --all
spv session submit <id> "Build a user auth system" --operation create
spv session status <id>
spv session process <jobId>
spv session delete <id> --force
```

Sessions use native SpecVerse commands with 98% token savings via schema caching (down from 245 lines of custom bash to 3 wrapper scripts). They support long-running AI workflows where you iterate over a spec with consistent context.

---

## Manifests

Manifests map **abstract capabilities** to **concrete technology implementations**. The spec defines WHAT; the manifest defines HOW.

```yaml
# manifests/implementation.yaml
specVersion: "5.1.1"
version: "1.0.0"
name: "my-project"

# Link to the deployment in your spec
deployment:
  deploymentSource: "./specs/main.specly"
  deploymentName: "production"

# Instance factories for code generation
instanceFactories:
  - name: "FastifyPrismaAPI"
    source: "@specverse/engines/libs/instance-factories/applications/fastify-prisma.yaml"

# Default technology mappings
defaults:
  controller: "FastifyAPI"
  storage: "PostgreSQL15"
  view: "ReactAppRuntime"

# Capability-to-instance-factory mappings
capabilityMappings:
  - capability: "api.rest.crud"
    instanceFactory: "FastifyPrismaAPI"
  - capability: "storage.database"
    instanceFactory: "PrismaPostgres"
  - capability: "view.webapp"
    instanceFactory: "ReactAppRuntime"
```

Swap the manifest to change the entire technology stack — Express instead of Fastify, MongoDB instead of PostgreSQL — without changing the spec. See [SPECVERSE-REALIZING.md](SPECVERSE-REALIZING.md) for full depth on instance factories, capability resolution, and how realize executes the manifest.

---

## Project-level scripts

Beyond the `spv` CLI, `specverse-self/scripts/` ships utility scripts used in the release ritual and documentation audits. The most useful set is under `scripts/indexing/` — four Node scripts that hash-index repos, audit documentation coverage (R28), compare content across repos, and generate the canonical `DOCUMENTATION-INDEX.md`.

```bash
cd specverse-self

node scripts/indexing/repo-indexer.mjs --all       # refresh .specverse-index.json in every repo
node scripts/indexing/guides-coverage.mjs          # R28 coverage gate
node scripts/indexing/docs-index.mjs               # regenerate DOCUMENTATION-INDEX.md
node scripts/indexing/repo-compare.mjs --summary   # drift + duplicate check
```

All four are idempotent, fast (< 2s total for all four across 4 repos), and safe to run at any time. Per R29 — run the set before every major release. See **[`scripts/indexing/README.md`](../../scripts/indexing/README.md)** for detailed usage, exit codes, and extension points.

Other script groups under `scripts/`:
- `scripts/smoke.sh`, `scripts/smoke-new-user.sh`, `scripts/smoke-new-user-static.sh`, `scripts/smoke-contract.sh`, `scripts/smoke-all.sh` — smoke test orchestration
- `scripts/compose-examples.mjs` — compose the 54 examples from entity modules
- `scripts/setup-variants.sh` — preps 6 parallel `spv init` variants for interactive testing

## Publishing

For publishing `@specverse/*` packages themselves (contributor ritual), see [PUBLISHING.md](../PUBLISHING.md) — the step-by-step publish checklist covering pre-publish verification, the publish order (types → entities → runtime → engines → self), OTP handling, and post-publish verification via `verify:published`.

Key scripts the ritual uses:

| Script | Purpose | When to run |
|---|---|---|
| `npm test` | Build + vitest + bootstrap promote | Before bumping versions |
| `./scripts/smoke.sh` | In-repo end-to-end with bootstrap CLI | Before bumping versions |
| `npm run verify:tarball` | Pack + install globally from tarball + `spv smoke` | **Before publishing** |
| `npm run verify:tarball:static` | Same but for ReactAppStarter path | **Before publishing** if touching view generation |
| `npm run verify:published` | Install `@latest` from npm + `spv smoke` | **After publishing** |
| `npm run smoke:all` | Full release gate | Final check before tagging |

---

## Related

- [SPECVERSE-INTRO.md](SPECVERSE-INTRO.md) — the documentation hub
- [SPECVERSE-SPECIFYING.md](SPECVERSE-SPECIFYING.md) — write the `.specly` files the CLI operates on
- [SPECVERSE-REALIZING.md](SPECVERSE-REALIZING.md) — deep dive on `spv realize` internals
- [SPECVERSE-APP-DEMO.md](SPECVERSE-APP-DEMO.md) — dynamic runtime interpreter (alternative to `spv realize` for fast feedback)
- [PUBLISHING.md](../PUBLISHING.md) — the publish ritual for `@specverse/*` packages
