# Forma Technical Specification
> **Status:** Pre-alpha research platform (branch `feat/milestone-a-contracts-verification-cli`, baseline `25c1753`, package `@forma-language/forma` `0.7.0`). APIs, wire formats, and package boundaries are evolving. This specification strictly distinguishes implemented behavior from proposed and deferred work; see [§9 Maturity & Boundaries](#_9-maturity-and-boundaries).
---
## 1. Identity & Architecture Overview
Forma is a **content-addressed, effect-tracked semantic kernel and programmable typed Lisp** whose domain vocabulary lives in ordinary preludes rather than hardcoded compiler special cases. A single TypeScript/Effect engine (`packages/ts/`) powers the CLI, Host ABI, LSP, MCP server, browser playground, and code generators. Forma programs either evaluate under capability-scoped host boundaries or elaborate into canonical typed IR and native [Effect](https://effect.website/) TypeScript.
### End-to-End Pipeline
```text
.lisp source (+ forma.json / forma.lock / preludes)
│
▼ Layer 1 — Lossless Reader (packages/ts/src/reader/)
Green/Red CST (trivia + exact spans) ──▶ SExpr + Formatter + Node IDs + Edit Scripts
│
▼ Layer 2 — Expander & Elaborator (packages/ts/src/expander/, surface/, descriptor/)
Hygienic macro expansion (step/time budgets, source-trace)
──▶ `form` descriptor reflection (:types, :scope, :check, :ir, Declares/Refers)
──▶ Core lowering (CoreExpr) + Canonical IR (language-ts-artifact/v1, irContractId)
│
▼ Layer 3 — Unified Type & Effect Checker (packages/ts/src/type/)
Single HM solver (pure + DSL + Effect) · Closed-SCC memoization
· Closed-shape rows (Pick/Omit/Merge) · Literal refinements · Exhaustive matches
· Operational Effect · Signature polymorphism (RFC 0023 §§1–3, 5) · Typed holes (?name)
│
├───────────────────────────┬──────────────────────────────┐
▼ Layer 4 — Backends ▼ Layer 4 — Runtime ▼ Layers 5–6 — Store & Verification
Effect TS / Effect Schema Kernel Evaluator & Bytecode VM DefHash (def:v1) + Tarjan SCC (scc:v1)
RPC · HTTP API · Cluster createLanguage / checkedRun DefinitionIndex + EvidenceCache (v1)
System Graph Linker CapabilityManifest + onHostCall TransactionalStore (snap:v1, CAS)
Foldkit (Elm) · Email forma-journal/v1 record/replay RFC 0027 Contract Diffs & Migrations
RFC 0028 workflow-laws BFS Explorer
│
▼ Layer 7 — Tooling & Surfaces (packages/host/, packages/language-server/, packages/editor/)
forma CLI · JSON ABI (v0.2.0) · Daemon · MCP · LSP · 23 Browser-Safe Bundles · Web Worker Playground
```
### Core Architectural Invariants
| Invariant | Enforcement mechanism |
| --- | --- |
| Domain neutrality | Domain forms (`entity`, `endpoint`, `rpc`, `cluster`, `workflow`, `rule`) are defined in `preludes/*.lisp` via `form` descriptors, not compiler special cases. |
| Single semantic engine | One TypeScript/Effect engine (`packages/ts/`) serves Node, browser Web Workers, LSP, MCP, and Host ABI. The prior OCaml engine is retired. |
| Author-anchored diagnostics | Macro expansion and elaboration preserve `source-trace` provenance; type, check, and runtime errors report author-written spans. |
| Explicit authority | No ambient globals, dynamic `eval`, or mutable module cells; side effects are typed as closed, operation-granular `Effect` requirement sets. |
| Browser-safe core | 23 runtime-neutral exports of `@forma-language/forma` have zero `node:*`, React, CodeMirror, MCP, or LSP imports (verified in CI). |
---
## 2. Layer 1 — Syntax & Lossless Reader
Source files use `.lisp`; project manifests use `forma.json` and `forma.lock`.
| Component | Path | Behavior |
| --- | --- | --- |
| Lexer & parser | `packages/ts/src/reader/lexer.ts`, `parser.ts` | Tokenizes lists `(...)`, vectors `[...]`, maps `{...}`, sets `#{...}`, symbols, keywords (`:k`), strings, numbers (`Int` vs `Float`), booleans, and comments with error recovery for partial documents. |
| Green/Red CST | `packages/ts/src/reader/green-tree.ts`, `red-tree.ts` | Immutable syntax tree preserving all whitespace and comment trivia with exact byte/line/column `Span`s. Supports `nodeAtOffset`, `elementAtOffset`, `elementsInRange`. |
| `SExpr` projection | `packages/ts/src/reader/to-sexpr.ts`, `types.ts` | Converts CST into `List`, `Vector`, `SMap`, `SSet`, `Sym`, `Str`, `Num`, `Bool`, `ErrorNode` retaining source locations. |
| Formatter | `packages/ts/src/Formatter.ts` | Lossless source formatting (`forma fmt` and LSP formatting). |
| Node identity & edit scripts | `packages/ts/src/editor/`, `packages/host/src/ts-host.ts` | Assigns stable structural node IDs, symbol references, node descriptions, slot affordances, an outline codec, and ID-addressed edit scripts (return edited source + identity without mutating session state). |
---
## 3. Layer 2 — Expansion & Elaborator Reflection
### Hygienic Macro Expansion
`packages/ts/src/expander/expand.ts` expands user and prelude macros before lowering:
- **Hygiene:** Fresh binding counters and `GensymScope` prevent accidental capture across macro boundaries; `authorNames` recovers author-facing names for diagnostics.
- **Expansion budgets:** `ExpansionBudget` bounds synchronous expansion by cumulative step count (`DEFAULT_MACRO_STEP_LIMIT = 10_000`, `maxExpansionSteps` → diagnostic `limit/expansion`) and wall-clock deadline (`timeoutMs` / `deadlineMs` → `limit/time`).
- **Source provenance:** `packages/ts/src/evaluator/source-trace.ts` (`markExpansion`, `tagExpandedExpr`, `copySourceTrace`, `sourceLocOf`, `sourceOriginsOf`) links every expanded form back to its call site and origin chain.
### `form` Descriptors & Elaborator Reflection
Preludes register domain syntax through `(form (head pattern ...) :types {...} :ir IRType body)` (`packages/ts/src/surface/form.ts`, `packages/ts/src/descriptor/`).
| Clause | Role |
| --- | --- |
| `:types` | Maps each pattern hole keyword to a surface type (`Symbol`, `Type`, `Syntax`, `RuntimeExpr`, `(Expr T)`, `(Declares Kind [String])`, `(Refers Kind)`, `(Record T)`, `(List T)`, etc.). |
| `:ir` | Names the canonical IR output type produced by the form body. |
| `:type` / `:infer-fn` | Optional result type or compile-time typing hook invoked during HM application inference. |
| `:scope` | Compile-time hook returning a record of local bindings introduced into body/child holes. |
| `:check` | Compile-time validation hook returning structured diagnostics with `:at` paths mapped back into authored syntax. |
| `:examples` | Checked documentation examples verified by `forma prelude check` and `pnpm check`. |
| `:emit` / `:graph` | Backend emission and system-graph extraction hooks (used by RPC, HTTP API, Cluster, and linker preludes). |
| `:extensions` | Form-local constant extensions. |
- `Declares` registers named declarations in the semantic environment; `Refers` resolves symbol or string references against declared kinds and reports candidate lists on mismatch.
- Prelude loads evaluate, infer, and metacheck all descriptor clauses, hook references, slot references, validators, and named payload contracts before atomically committing the prelude scope.
### Canonical IR & Payload Contract Identity
`packages/ts/src/artifact/` packages validated elaborated declarations into immutable artifacts:
- **Envelope:** `language-ts-artifact/v1`, digested with SHA-256 over canonical JSON (sorted object keys).
- **`irContractId` (`packages/ts/src/artifact/contract-identity.ts`):** SHA-256 over the root IR type name and the canonical syntax (layout/comments stripped, map/set entries sorted) of every transitively reachable type definition. Forms with different surface syntax that target the same IR definitions share an `irContractId`. Metadata edits change `irContractId`.
- **`payloadConstraintsId` (`payloadContractId`):** SHA-256 over canonical JSON of resolved descriptor payload constraints when no `:ir` type is attached.
- **Boundary:** `irContractId` / `payloadContractId` identify a payload schema snapshot, not directional wire compatibility (handled by Layer 6 / RFC 0027) or function behavior identity (handled by Layer 5 / RFC 0029).
---
## 4. Layer 3 — Unified Type & Effect System
All pure, DSL, and Effect programs check through **one Hindley–Milner typechecker** (`packages/ts/src/type/`); the legacy `mechanics/check.ts` solver is retired (`mechanics/types.ts` remains solely as the IR/codegen projection representation).
| Feature | Implementation (`packages/ts/src/type/`) | Details & current limits |
| --- | --- | --- |
| Core HM & lowering | `lower*.ts`, `infer-core.ts`, `unify.ts`, `substitution.ts`, `scheme-ops.ts` | Parametric polymorphism, let-generalization, typeclasses (`typeclass.ts`), closed-SCC per-document memoization (`scc-memo.ts`). Numeric `Int` vs `Float` distinction (`Int` checks JS safe integer range); unannotated arithmetic widens to `Float`. |
| Record rows | `infer-record.ts`, `data-relation.ts` | Closed-shape row operations `Pick`, `Omit`, `Merge` (RFC 0005). Optional record fields accept existing `Option` values. Qualified open-row polymorphism (RFC 0006) is deferred. |
| Algebraic data types, open variants & exhaustiveness | `infer-typedef.ts`, `infer-control.ts`, `variant.ts` | Tagged unions (`Tagged`, including GADTs & existentials), nominal brands (`Brand`), structural open/closed polymorphic variants (`(Variant ... & e)` + `(variant :Tag val)`, RFC 0030), qualified constructor preservation through local bindings and collection joins. Non-exhaustive closed-constructor/closed-variant `match` expressions fail with error severity. |
| Literal refinements | `infer-core.ts`, `data-relation.ts` | Compile-time checking of literal values against numeric/string refinement predicates. General SMT/solver-backed refinements are not implemented. |
| Operational `Effect` & direct-style `handle` | `infer-effect.ts`, `effect-check.ts`, `effect-sets.ts`, `authority.ts` | Tracks success type `A`, closed error union `E`, and operation-granular requirement set `R` (e.g., `[CartRepo.load Pricing.price]`). Supports direct-style effect calls without `do!`/`pure` and unified tail-resumptive `handle` (`Service.method` + `fail`, RFC 0003 Stage 1), alongside backwards-compatible `do!`, `service`, `error`, `layer`, `class`, `catch`, `provide`, resources, concurrency, streams. |
| Effect signature polymorphism | `effect-sets.ts`, `infer-effect.ts` | **RFC 0023 Stages 1–3 & 5 implemented:** error-set and requirement-set variables in Effect signatures let higher-order wrappers pass callback effects through without over-approximation. **Stages 4 & 6 (`without` row subtraction) remain proposed.** |
| Typed holes | `holes.ts` | Any lowered variable starting with `?` (e.g. `?next`) emits diagnostic `typecheck/hole` (error severity) containing the expected inferred type and up to 10 in-scope bindings whose instantiated scheme unifies with the goal (restoring solver state per trial). |
---
## 5. Layer 4 — Backends & Runtime Boundaries
### Code Generation Backends
| Backend | Entry point / Prelude | Output & guarantees |
| --- | --- | --- |
| Effect TypeScript | `generateEffectProgram` (`@forma-language/forma/mechanics`) | Reads, projects, checks, and emits Effect 4 TypeScript (`Context.Service`, `Schema.TaggedError`, `Effect.gen`, layers, resources, streams). Returns located diagnostics on check failure; throws on untranslatable body nodes (never emits placeholders). |
| Effect Schema | `generateMechanicsEffectSchemaModule` | Emits `Schema.Struct`, `Schema.brand`, `Schema.optionalKey`, `Schema.Array`, tagged unions, and JSON Schema codecs (`forma schema`). |
| Unary RPC | `preludes/rpc.lisp`, `@forma-language/forma/rpc` | Native Effect unary RPC definitions and named groups with shared schema imports. |
| HTTP API | `preludes/http-api.lisp`, `@forma-language/forma/http-api` | Checked HTTP API declarations and native Effect HTTP modules. |
| Cluster entities (prototype) | `preludes/cluster.lisp`, `@forma-language/forma/cluster` | Pure checked state transitions, required deduplication keys for persisted commands, native `Entity.make`/`toLayer`. In-memory state only; runners/storage/workflows/cron not implemented. |
| System graph linker | `generateEffectSystem` (`@forma-language/forma/effect-system`) | Output-neutral linker combining RPC, HTTP API, Cluster, and ordinary Effect modules into one checked module plus a typed system graph (services, operations, endpoints, RPCs, entities, relations). |
| Foldkit / Elm (prototype) | `preludes/elm.lisp`, `@forma-language/forma/elm` | Exhaustive message updates, typed command recovery, pure Hiccup views. Command args, subscriptions, and shared HTTP client generation remain proposed. |
| Email rules (prototype) | `preludes/email.lisp`, `@forma-language/forma/email` | Closed lanes, first-match decisions, pure rules, typed delivery recovery. Scheduling, rate enforcement, and dry runs not implemented. |
### Execution & Host Safety Boundaries
- **Evaluator & Bytecode VM (`packages/ts/src/evaluator/`, `packages/ts/src/vm/`):** Tree-walking evaluator for compile-time/macro evaluation and stack bytecode VM (`opcodes.ts`, `vm.ts`) for runtime execution with cooperative step and wall-clock deadline checks (`limit/steps`, `limit/time`).
- **Embedding facade (`createLanguage`, `packages/host/src/language.ts`):** Promise-based API (`check`, `run`, `describe`, `emit`, `close`) requiring no Effect imports. Capabilities declare `arity` and a checked `typeScheme` (or explicit `untyped: true` opt-in). `check` never evaluates; `run` checks first and never retains definitions across calls.
- **`checkedRun` & `CapabilityManifest` (`packages/host/src/ts-host.ts`):** Pre-execution static inspection produces a `CapabilityManifest` listing reachable typed capabilities plus source/prelude SHA-256 digests. Grants support per-capability modes and call-count budgets.
- **`onHostCall` approval hooks & cooperative budgets:** Every suspended host call invokes `onHostCall({ call, args, span })` with author source spans, returning `{ action: "allow" }` or `{ action: "deny", reason }`. Cooperative budgets bound `steps`, `timeoutMs`, `hostCalls`, `maxExpansionSteps`, and `maxResultBytes`. Hard process isolation uses `node:worker_threads` (`examples/worker-isolation/`, `examples/flagship/`).
- **Deterministic host-call replay (`forma-journal/v1`, `packages/host/src/journal.ts`):** Records live host calls (`header` with source/prelude SHA-256 digests + `entries` with lossless `JournalValue` encoding, ordinal function matching, and optional redaction) to JSONL and deterministically replays them with zero live host calls, detecting program digest mismatches and call divergence (`forma run --record` / `--replay`).
---
## 6. Layer 5 — Content-Addressed Transactional Store (RFC 0029)
Implemented on branch `feat/milestone-a-contracts-verification-cli` across `packages/ts/src/store/` (browser-safe), `packages/ts/src/node/` (`.forma/store/` disk persistence), `packages/host/src/store-*.ts`, and `packages/host/src/cli/store.ts`.
### Content-Addressed Identity (`def-hash.ts`)
| Concept | Format / Mechanism | Rules |
| --- | --- | --- |
| `DefHash` | `def:v1:` | Hashes declaration kind (`define`, `type`, `error`, `service`, `layer`, `class`, `instance`, `form`, `macro`, `test`, `declaration`), alpha-normalized canonical core/SExpr AST (de Bruijn local binders, sorted map/set entries), resolved `DefHash` dependency refs, canonical type/effect signature, language profile (`forma-core-v1`), and participating macro/`form` descriptor `DefHash`es. |
| Mutual recursion | `scc:v1:` | Tarjan SCC (`computeSccs`) canonicalizes cycle groups into one `sccHash`; each member derives its `DefHash` deterministically from `(sccHash, memberIndex)`. |
| Metadata separation | `PresentationMeta` | Authored source, formatting, comments, docstrings, spans, and display names are stored outside `DefHash`. Editing docs or renaming a symbol never invalidates `DefHash` or downstream evidence. |
| Opaque boundaries | `OpaqueBoundaryRef` | Builtins, external npm/Effect packages, and native providers are pinned by `{ kind, name, signature, runtimeDigest }`. External JS is never falsely content-addressed. |
### Read-Only Index & Semantic Queries (`index-builder.ts`, `queries.ts`)
`DefinitionIndex` indexes `definitions` (`DefHash → DefinitionRecord`), `bindings` (`QualifiedName → DefHash`), `byName` (supporting coexisting versions), reverse `dependents`, and `metadata`. Supported queries: `getDefinition`, `findDependents` (direct/transitive), `findDependencies`, `queryByCapability`, `queryByError`.
### Hash-Keyed Evidence Cache (`evidence-cache.ts`, `toolchain-digest.ts`)
Immutable `forma-evidence/v1` records are keyed by:
```text
EvidenceKey = (defHash, kind, toolchainDigest, inputDigest) // serialized as evidence-key:v1
```
| `kind` | Payload | Cacheability guard (`checkEvidenceCacheability`) |
| --- | --- | --- |
| `typecheck` | `TypecheckEvidencePayload` (`ok`, `signature`, `requirements`, `errors`, `diagnostics`) | Cacheable while `toolchainDigest` (checker version + profile + prelude digests) matches. |
| `artifact` | `ArtifactEvidencePayload` (`canonical-ir` \| `effect-ts`, `content`, `contentHash`) | Cacheable while emitter + target profile match. |
| `test` | `TestEvidencePayload` (`passed`, `requirements`, `runnerProfile`, `deterministicRunner`) | **Rejected** unless `requirements.length === 0` **and** `deterministicRunner === true`. |
| `verification` | `VerificationEvidencePayload` (`result`, `bounds`, `assumptions`, `counterexample?`) | Stores explicit finite bounds & trust account; never cached as an unbounded proof. |
Every record carries an explicit `EvidenceTrustAccount` (`producer`, `version`, `profile`, `deterministic`, `assumptions`). Upgrading `toolchainDigest` invalidates affected evidence without rewriting historical definitions.
### Transactional Store & Optimistic Concurrency (`transactions.ts`, `tx-types.ts`, `projection.ts`)
```text
BranchRef { name, head } ──▶ Snapshot (snap:v1:) {
parent, bindings: Map,
metadata: Map,
policies: PolicySetHash (policy:v1:), policyConfig
}
```
- **Operations:** `add`, `update`, `rename` (O(1) binding/metadata update without rehashing callers), `remove`, `move`, tagged with `operationClass: "impl-edit" | "requirement-edit"`.
- **Interface impact classification (`isSameInterface`):**
- *Same-interface update* (resolved signature, error set, and requirement set unchanged): dependents rebind to the new `DefHash` without re-typechecking their bodies.
- *Interface-changing update* on a protected branch: governed by `onInterfaceChange` — `"reject"` (default, returns exact `unupdatedDependents`), `"staging-branch"`, or `"add-only"` (coexisting binding).
- **Optimistic CAS:** If the branch head advanced since `baseSnapshot`, disjoint transactions with no invalidated dependency hashes auto-rebase onto the current head; colliding transactions fail with a structured `ConflictReport` (`name-collision`, `dependency-changed`, `removed-dependency`).
- **Lossless `.lisp` projection:** `exportSnapshotToSources` emits `.lisp` modules preserving authored source for unchanged definitions; `importSourcesAsTransaction` parses edited `.lisp` files, diffs against the base snapshot, and submits the delta through the same transaction gate.
### Enforceable Branch Policies (`policies.ts`)
`evaluateBranchPolicies` enforces declarative snapshot policies inside every transaction:
| Policy | Enforcement |
| --- | --- |
| `dependencyBoundaries` | `allow` / `deny` edge rules between module/namespace prefixes. |
| `capabilityBudgets` | Maximum allowed `Effect` requirement sets per namespace (empty = pure namespace). |
| `requirementEdit` | Separates `impl-edit` from `requirement-edit` (tests, contracts, laws); can require explicit `approvedRequirementEdit: true`. |
| `evidenceGates` | Requires specified `EvidenceKind`s before commit; enforces deterministic tests and rejects `"inconclusive"` verification by default (`rejectInconclusiveVerification: true`). |
| `evolution` | Enforces `"add-only"` or `"backward-compatible"` rules on `publishedNamespaces` using RFC 0027 directional diffs (unless explicitly waived). |
---
## 7. Layer 6 — Contract Evolution & Bounded Verification (RFC 0027 & RFC 0028)
### Directional Contract Evolution (RFC 0027 Stages 1–2, `packages/ts/src/contracts/`)
- **Directional diffs (`diffContractSnapshots`):** Compares two validated `ContractSnapshot` graphs and yields `CompatibilityVerdict = "compatible" | "incompatible" | "unknown"` per role/direction (`unknown` never silently passes as `compatible`).
- **Roles & rules:** Request decoding (new server vs old client) vs response decoding (old client vs new server); field `optional` (absence) orthogonal to `nullable` (`null`); per-codec and per-record `UnknownFieldPolicy` (`"reject"` | `"ignore"`); exact `NumericInterval` and `StringRefinement` inclusion (distinct regex patterns yield `"unknown"`); error-set and requirement-set expansion; terminating pairwise comparison for recursive `ContractRefNode` graphs; stable declaration `id` / explicit rename map resolution; metadata-only changes separated from wire-breaking changes.
- **Checked pure migrations (`checkPureMigration`, `validateValueAgainstType`):** Validates authored pure migrations from old decoded type to new type against independent before/after fixtures, rejecting invalid outputs and reporting explicit information loss; inverse migrations are checked against round-trip laws over the declared domain.
- **Store integration:** `evaluateBranchPolicies` runs directional contract diffs for `evolution` policies on published namespaces.
### Bounded Finite-Model Verification (RFC 0028 Stage 1, `preludes/workflow-laws.lisp`, `packages/ts/src/verification/bounded-explorer.ts`)
- **Model & decidable subset:** The `workflow-laws` prelude defines finite `domains`, `initialStates`, `transitions` (`params`, `guard`, `update`), and safety `laws` (`when`, `holds`). Guards/updates/laws are restricted to `SUPPORTED_DECIDABLE_OPS` (boolean/control, structural equality, integer ordering, `+`/`-`, map/record ops, finite collection combinators, `let`, inline `fn`). Arbitrary hooks, native calls, effects, recursion, and floats are rejected as `"inconclusive"` (`unsupported-operation`).
- **Fixed-point BFS explorer (`exploreWorkflowModel`, `verifyWorkflowSource`):** Canonicalizes states (`canonicalizeState`), retains predecessor edges, and explores reachable states to a fixed point within configurable bounds (`maxStates` default `10_000`, `maxEdges` default `100_000`, optional `maxDepth` and `maxTimeMs`).
- **Verdicts & diagnostics:**
- `holds-in-model`: fixed-point exploration completed with zero law violations (reports vacuous laws and unreachable transitions explicitly).
- `counterexample`: shortest violating trace (`CounterexampleTrace`) linked to authored transition and law source spans.
- `inconclusive`: state/edge/depth/time budget exhausted, unsupported operation, or invalid model. Depth-bounded prefixes without a fixed point never report `holds-in-model`.
- **Store integration:** `toVerificationEvidencePayload` and `defaultVerificationTrustAccount` (pinning `workflow-laws-semantics/v1` and trusted components) feed `EvidenceCache` and `evaluateBranchPolicies` (which rejects `inconclusive` and `counterexample` verdicts on gated branches).
---
## 8. Layer 7 — Tooling & Surfaces
### CLI (`forma`, `packages/host/src/cli/`)
| Group | Commands |
| --- | --- |
| Human commands | `check `, `run [--unchecked] [--record ] [--replay ]`, `test [paths...] [--filter ]`, `fmt [--check]`, `repl [--prelude ]...`, `describe `, `explain `, `store ` (all support `--json` where applicable). |
| Machine / automation | `file `, `schema --out `, `prelude check `, `request ['']`, `daemon` (NDJSON), `mcp` (stdio MCP server + code-mode REPL), `lsp` (LSP stdio), `abi-schema`, `add\|update\|verify\|vendor`, `version`. |
### Host ABI, LSP, Distribution & Playground
- **Host ABI (`@forma-language/forma/host`, `packages/host/src/host-contract.ts`):** `HOST_ABI_VERSION = "0.2.0"`. Single operation registry derives request decoders, response projections, session scopes, and JSON Schema (`conformance/host-abi/schema.json`). Supports `parse`, `typecheck`, `evaluate`, `checkedRun`, `observe`, `emit`, `emitMany`, `emitBackends`, `artifactSummary`, `replSubmit`, structural editor operations, and store query/transaction operations.
- **Language Server (`forma-language-server`, `packages/language-server/`):** Multi-file LSP resolving local imports, `forma:*` libraries, and `forma.json` packages over memoized `@forma-language/forma/analysis` queries (diagnostics, hover, completion, definition, references, rename, document symbols, semantic tokens, formatting). Domain-neutral by default; loads consumer preludes via `FORMA_LANGUAGE_SERVER_PRELUDES`.
- **Single distribution & browser boundary (`@forma-language/forma` `0.7.0`):** Exposes 27 package export paths total: **23 runtime-neutral browser-safe bundles** (verified by `scripts/check-distribution.mjs` to import zero `node:*`, React, CodeMirror, Lezer, MCP, or LSP packages), 2 Node-conditional exports (`./node`, `./language-server`), and 2 optional UI editor adapters (`./editor/codemirror`, `./editor/react`). Peer requirement: `effect ^4.1.1`; tooling peers (`@modelcontextprotocol/sdk`, `vscode-languageserver`, CodeMirror, React) are optional.
- **Browser Playground (`apps/website/`):** Executes the TypeScript engine in a Web Worker, exposing every compilation stage from editable source to target output (Effect TS, Effect Schema, canonical IR).
---
## 9. Maturity and Boundaries
| Capability | Status | Scope / Caveat |
| --- | --- | --- |
| Lossless reader, formatter, CST, node IDs, edit scripts | **Shipped (`main`)** | Pinned by surface goldens and Host ABI fixtures. |
| Hygienic macros, expansion budgets, `form` descriptors, canonical IR (`irContractId`) | **Shipped (`main`)** | Hook-returned types/scopes are not yet re-checked by an independent core kernel. |
| Unified HM + operational `Effect`, rows (`Pick`/`Omit`/`Merge`), literal refinements, exhaustive matches, typed holes (`?name`) | **Shipped (`main`)** | Unannotated arithmetic widens to `Float`; some local-def / 0-arg gaps remain (RFC 0019). |
| Effect signature polymorphism (RFC 0023 Stages 1–3 & 5) | **Shipped (`main`)** | **Stages 4 & 6 (`without` subtraction) remain proposed.** |
| Effect TS / Schema / RPC / HTTP API / System Linker codegen | **Shipped (`main`)** | Cluster, Foldkit (Elm), and Email preludes are **prototypes** (see §5 limits). |
| `createLanguage`, `checkedRun`, `CapabilityManifest`, `onHostCall`, cooperative budgets, `forma-journal/v1` replay | **Shipped (`main`)** | Cooperative VM budgets; OS/process isolation uses host `node:worker_threads`. |
| Multi-file LSP, `forma` CLI, `forma mcp`, Host ABI `0.2.0`, 23 browser-safe bundles | **Shipped (`main`)** | Package `@forma-language/forma` is prepared (`0.7.0`) but **not yet published to npm**. |
| Content-addressed transactional store, `DefHash`/SCC, `EvidenceCache`, branch policies, `forma store` CLI (RFC 0029) | **Implemented on this branch (`25c1753`)** | Not yet merged to `main`; local `.forma/store/` + in-memory backends (no distributed consensus/CRDT). |
| Directional contract diffs & checked pure migrations (RFC 0027 Stages 1–2) | **Implemented on this branch (`25c1753`)** | Not yet merged to `main`; regex implication and opaque native codecs yield `unknown`. |
| `workflow-laws` prelude & finite-model BFS explorer (RFC 0028 Stage 1) | **Implemented on this branch (`25c1753`)** | Not yet merged to `main`; finite-model verification only (no SMT solver). |
| Independent trusted core checker (RFC 0022 Stage 1) | **Proposed / Planned** | Current HM checker & elaborator remain in the trusted computing base. |
| Cacheable seeded/property Effect tests & local providers (RFC 0014 / RFC 0015) | **Proposed / Planned** | `EvidenceCache` deterministic-test guard is wired; Effect test doubles/generators remain planned. |
| Restricted solver profile `forma/refined` (RFC 0028 Stage 2) | **Proposed / Planned** | Contingent on finite-model consumer validation; no SMT/Lean backend exists. |
| Live browser store demo, Gate 3 multi-agent Effect TS benchmark, npm publish | **Proposed / Planned** | Gate 3 target (≥7/8 hard-tier tasks, ≤2 median repair rounds) is an acceptance target, not a result. |
| Direct-style effect bodies & unified tail-resumptive `handle` (RFC 0003 Stage 1) | **Implemented (Effect 4 TS + `runEffectProgram`)** | Backwards-compatible with `do!`/`pure`/`catch`/`provide`/`layer`; unannotated effect inference, evidence-passing JS, and Perceus-FBIP native/Wasm backends remain planned. |
| Structural open polymorphic variants (RFC 0030) | **Implemented (HM checker, evaluator, VM)** | `(Variant ... & e)` + `(variant :Tag val)`; Effect 4 TS/Schema lowering for structural `Variant` types remains planned. |
| Go/Rust Effect hosts (RFC 0022), non-Forma Lisp emitters (RFC 0021), qualified open rows (RFC 0006–0009), grammar descriptions (RFC 0024) | **Deferred (off critical path)** | Stage 0 Clojure macro spellings (`preludes/modules/clojure.lisp`) remain supported as-is. |