A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
docs: add Diataxis onboarding suite, Mermaid architecture diagrams, and runtime guide
wrong-nebulaeb7d3ac126e2
diff --git a/README.md b/README.mdindex 2be44e2..a969062 100644--- a/README.md+++ b/README.md@@ -115,6 +115,81 @@ const png = await renderPng(`flange = box(4, 2, 0.4) | cut(cyl(0.5, 1))`, 512);---+## Where Forma Runs (Edge, Cloud, Agent VMs & Air-Gapped Sandboxes)++Because `wasm/forma.wasm` is a **~0.8 MB zero-import WebAssembly module** (zero WASI, zero top-level `node:*` imports) and the static Linux builds are **~1.3 MB LTO `musl` binaries** (no GPU, ~6–14 MB RAM), Forma runs almost anywhere:++| Environment | Providers / Runtimes | How to Run |+|---|---|---|+| **Edge & Browsers** | Cloudflare Workers, Vercel Edge, Netlify Edge, Deno Deploy, Supabase Edge Functions, Fastly Compute, Chrome/Safari/Firefox | Zero-boilerplate on Cloudflare Workers (`workerd` auto-imports `forma.wasm`); `forma-3d/edge` + `forma-3d/forma.wasm` (or `fetch()`) everywhere else |+| **Serverless & Containers** | AWS Lambda (`x86_64` & Graviton `aarch64`), ECS/Fargate, App Runner, Cloudflare Containers, Google Cloud Run, Fly.io, Azure, Railway, Render | `npm install forma-3d` on Node runtimes, static `musl` binary, or the ~2 MB `FROM scratch` [`Dockerfile`](Dockerfile) (`forma-server`) |+| **Agent VMs & Notebooks** | `boat.dev`, Modal, E2B, Daytona, Google Colab, Kaggle, Codespaces, Gitpod | `npx -y forma-3d`, `cargo build --release`, or static Linux binary |+| **No-Network Sandboxes** | ChatGPT VM (Code Interpreter / Custom GPTs), air-gapped AWS Lambda & containers | Upload `forma-sandbox-linux-x86_64.zip` from GitHub Releases (static `forma` + zero-dep [`sandbox/forma.py`](sandbox/forma.py) + `SKILL.md`) |++### Cloudflare Workers / Edge / Browsers++`forma-3d` has zero top-level `node:*` imports. On Cloudflare Workers, the `workerd` export condition automatically selects [`lib/workerd.mjs`](lib/workerd.mjs) (which statically imports `../wasm/forma.wasm` for Wrangler's built-in `CompiledWasm` rule and auto-recovers the cached WASM instance if an isolate ever traps):++```js+// Cloudflare Worker (zero boilerplate, no nodejs_compat required)+import { exportMesh } from "forma-3d";++export default {+ async fetch(req) {+ const glb = await exportMesh(await req.text(), "glb", { strict: true });+ return new Response(glb, { headers: { "content-type": "model/gltf-binary" } });+ },+};+```++```js+// Vercel Edge / Netlify Edge / Fastly (import ends in .wasm to match bundler rules)+import formaWasm from "forma-3d/forma.wasm";+import { exportMesh } from "forma-3d";+const glb = await exportMesh("a = box(1, 1, 1)", "glb", { wasm: formaWasm });++// Browser / Web Worker+import { loadForma } from "forma-3d/edge";+const engine = await loadForma(fetch("/forma.wasm"));+```++### No-Network Sandboxes (ChatGPT VM & AWS Lambda Python)++GitHub Releases include static `x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl` binaries (`forma` CLI and `forma-server`) plus a single-file offline kit (`forma-sandbox-linux-x86_64.zip` containing `forma`, [`sandbox/forma.py`](sandbox/forma.py), and `SKILL.md`). `sandbox/forma.py` automatically copies the binary to `/tmp/forma` with `chmod +x` when mounted on a `noexec` volume (such as `/mnt/data` in ChatGPT's VM):++```python+import sys, zipfile+zipfile.ZipFile("/mnt/data/forma-sandbox-linux-x86_64.zip").extractall("/tmp/forma_kit")+sys.path.insert(0, "/tmp/forma_kit")+import forma++print(forma.eval_pipe(+ "flange = box(4, 2, 0.4) | cut(cyl(0.5, 1))",+ out="/mnt/data/flange.glb",+ render="/mnt/data/flange.png",+))+```++---++## Documentation++Start from the [**Documentation Hub (`docs/README.md`)**](docs/README.md) or jump straight to a guide:++| Goal | Guide |+|---|---|+| Build your first watertight 3D part step by step | [Tutorial: Build your first watertight 3D part](docs/tutorials/first-part.md) |+| Connect Claude Code, Cursor, Codex, ChatGPT VM, or local LLMs | [How to connect AI agents (MCP, CLI, GBNF & Sandboxes)](docs/how-to/connect-ai-agents.md) |+| Embed `forma-3d` in Node.js, Cloudflare Workers, Edge, or browsers | [How to embed forma-3d in JS, Edge, and Browsers](docs/how-to/embed-wasm-js.md) |+| Deploy `forma-server`, Docker, AWS Lambda, or offline sandboxes | [How to deploy Forma (HTTP, Docker, Cloud & Sandboxes)](docs/how-to/deploy-http-server.md) |+| Author in `mm`/`in` or heal & decimate existing meshes | [How to work with units and process existing meshes](docs/how-to/units-and-mesh-processing.md) |+| CLI flags, exit codes, and native vs WASM parity | [Reference: CLI (`forma` and `forma-3d`)](docs/reference/cli.md) |+| `Forma-Pipe`, `Forma-DSL`, units, and format matrix | [Reference: Language, units, and formats](docs/reference/language-and-formats.md) |+| MCP schemas, JS/TS/Edge API, and HTTP endpoints & limits | [Reference: MCP, JS/TS/Edge, and HTTP APIs](docs/reference/apis.md) |+| Design rationale, 6-crate workspace, and transactional kernel | [Why Forma exists](docs/explanation/why-forma.md) · [Architecture](docs/explanation/architecture.md) |++---+## BenchmarksAll models were evaluated head-to-head on stock headless **Blender 5.3.0 (`bpy`)** vs **Forma (`Forma-Pipe`)** across 6 cross-category exact-dimension tasks (`flange_plate`, `pipe_tee`, `beveled_enclosure`, `hex_nut`, `subdiv_mug`, `pedestal_bowl`), verified independently with `trimesh` + `scipy` (Chamfer distance, Hausdorff-99, Generalized Winding Number Volumetric IoU, watertight/0-non-manifold checks, and 16-layer planar sliceability).diff --git a/docs/README.md b/docs/README.mdnew file mode 100644index 0000000..af5ac3e--- /dev/null+++ b/docs/README.md@@ -0,0 +1,77 @@+# Forma Documentation++Forma (`v0.4.2`) is a headless, pure-Rust 3D polyhedral modeling engine built for AI agents, edge runtimes, CI pipelines, and developers. It runs through a native CLI (`forma`), a zero-dependency universal npm WASM package (`forma-3d` for Node.js, Cloudflare Workers, Edge, and browsers), an MCP stdio server (`forma-mcp` / `forma-3d-mcp`), an opt-in HTTP microservice (`forma-server`), and an offline Python sandbox kit (`sandbox/forma.py`).++```mermaid+flowchart LR+ subgraph Callers+ A["AI Agent (MCP / CLI)"]+ B["JS / Edge / Browser App"]+ C["HTTP Client / Sandbox"]+ end+ subgraph Surfaces["Runtime Surfaces"]+ S1["forma-cli / forma-mcp"]+ S2["forma-3d (WASM / workerd / edge)"]+ S3["forma-server (HTTP / scratch)"]+ end+ subgraph Core["Shared Pure-Rust Core"]+ L["forma-lang (Pipe / DSL / GBNF)"]+ K["forma-core (f64 PolyMesh + CoW + Invariants)"]+ end+ subgraph Outputs["Verified Artifacts"]+ O1["GLB / STEP / 3MF / STL / OBJ"]+ O2["4-View PNG / 3-View SVG"]+ end+ A --> S1+ A --> S2+ B --> S2+ C --> S3+ S1 --> L+ S2 --> L+ S3 --> L+ L --> K+ K --> O1+ K --> O2+```++## Choose a starting point++| If you want to... | Start here |+| --- | --- |+| Build and verify your first 3D part from scratch | [Tutorial: Build your first watertight part](tutorials/first-part.md) |+| Connect Claude Code, Cursor, Codex, ChatGPT VM, or a local LLM | [How to connect AI agents (MCP, CLI, GBNF, and Sandboxes)](how-to/connect-ai-agents.md) |+| Embed `forma-3d` in Node.js, Cloudflare Workers, Edge, or browsers | [How to embed forma-3d in JS, Edge, and Browsers](how-to/embed-wasm-js.md) |+| Deploy to AWS, Cloudflare, Docker, `boat.dev`, or air-gapped VMs | [How to deploy Forma (HTTP, Docker, Cloud, and Sandboxes)](how-to/deploy-http-server.md) |+| Model in millimeters/inches or clean up existing meshes | [How to work with units and process existing meshes](how-to/units-and-mesh-processing.md) |+| Look up CLI flags, exit codes, and native vs WASM parity | [Reference: CLI (forma and forma-3d)](reference/cli.md) |+| Look up `Forma-Pipe`, `Forma-DSL`, spec topics, and formats | [Reference: Language, units, and formats](reference/language-and-formats.md) |+| Look up MCP tool schemas, JS/TS/Edge API, and HTTP endpoints | [Reference: MCP, JS/TS, and HTTP APIs](reference/apis.md) |+| Understand why Forma uses polyhedral invariants and strict budgets | [Explanation: Why Forma exists](explanation/why-forma.md) |+| Understand the 6-crate workspace and transactional kernel | [Explanation: Architecture](explanation/architecture.md) |++## Agent entry points++These root files are packaged inside the `forma-3d` npm tarball and tuned for coding agents:++- [`SKILL.md`](../SKILL.md): Drop-in agent skill with four smoke-tested `Forma-Pipe` recipes.+- [`AGENTS.md`](../AGENTS.md): Compact agent workflow rules and CLI/MCP invocation guide.+- [`llms.txt`](../llms.txt): Self-contained machine-readable language cheat sheet and repository index.+- [`grammar/forma_pipe.gbnf`](../grammar/forma_pipe.gbnf): Formal GBNF grammar for constrained local-LLM decoding.++## Contributor docs and blueprints++- [`CONTRIBUTING.md`](../CONTRIBUTING.md): Hard budgets for binary size, MCP tokens, strict manifoldness, and opt-in crates.+- [`ROADMAP.md`](../ROADMAP.md): Project roadmap and milestone status.+- [`contribute/README.md`](../contribute/README.md): Design blueprints for planned opt-in addons (`forma-print`, `forma-ue`, craftsmanship, retopology feasibility).++## Archived benchmark and engineering reports++Historical phase reports and verification records remain at their original paths:++- [Extended Benchmark Report (12 models across 10 labs)](EXTENDED_BENCHMARK_REPORT.md)+- [Independent Automated Verification Report](VERIFICATION_REPORT.md)+- [Phase 1.1: Blender 5.3 Architecture Audit](PHASE1_ARCHITECTURE_AUDIT.md)+- [Phase 1.2: Headless Blender Baseline Report](PHASE1_BASELINE_REPORT.md)+- [Phase 2.4: Command Language Ablation](PHASE2_LANGUAGE_ABLATION.md)+- [Autoresearch Hill-Climb Log](AUTORESEARCH_HILLCLIMB.md)+- [Interactive HTML Showcase (`docs/showcase.html`)](showcase.html)diff --git a/docs/explanation/architecture.md b/docs/explanation/architecture.mdnew file mode 100644index 0000000..28eb2d6--- /dev/null+++ b/docs/explanation/architecture.md@@ -0,0 +1,86 @@+# Architecture++Forma is organized as a single pure-Rust geometry and language core surrounded by four thin runtime surfaces: a native CLI, a stdio MCP server, a universal WebAssembly npm package (`forma-3d` for Node, Cloudflare Workers, Edge, and browsers), and an opt-in HTTP microservice (`forma-server`). Every surface delegates parsing, execution, invariant verification, rendering, and export to the same underlying crates so a modeling script produces identical geometry regardless of where it runs.++## Six crates, two membership tiers++The Cargo workspace splits six crates into two explicit tiers to protect compile times, binary size, and zero-dependency portability:++```mermaid+flowchart LR+ subgraph OptIn["Opt-In Workspace Crates (excluded from default-members)"]+ W["forma-wasm (wasm32 + wasm-opt)"]+ SRV["forma-server (HTTP/1.1)"]+ IMG["FROM scratch (~2 MB musl)"]+ SRV --> IMG+ end+ subgraph Core["default-members (Core)"]+ CLI["forma-cli (forma)"]+ MCP["forma-mcp (stdio MCP)"]+ LANG["forma-lang (Pipe / DSL / GBNF)"]+ CORE["forma-core (f64 PolyMesh + Invariants)"]+ CLI --> LANG+ MCP --> LANG+ LANG --> CORE+ end+ W -. "wasm-release" .-> LANG+ SRV -. "static-release" .-> LANG+```++### Default core (`default-members`)++- **`forma-core`**: The double-precision (`f64`) polyhedral modeling kernel. It owns `PolyMesh` storage, semantic face/edge selectors, BVH-localized tolerance-guided CSG booleans with coplanar tie-breaking and perturbation retry, subdivision and bevel/shell/deform/curve/UV/remesh modifiers, the `Scene` transaction manager, `MeshInvariants`, the pure-Rust software PNG rasterizer and SVG orthographic drafter, the `Unit` model, and all native exporters/importers.+- **`forma-lang`**: The language front end. It implements the `Forma-Pipe` pipeline dialect, the line-oriented `Forma-DSL` compact dialect, the embedded GBNF grammar (`grammar/forma_pipe.gbnf`), and the compiled core and Tier-1 progressive topic specifications.+- **`forma-cli`**: The native command-line binary (`forma`). It wires terminal flags, exit codes, and the optional external Blender `.blend` bridge onto `forma-lang` and `forma-core`.+- **`forma-mcp`**: The native stdio JSON-RPC 2.0 MCP server (`forma-mcp`). It exposes exactly four tools (`eval`, `inspect`, `tx`, `export`) within the strict `< 800` `o200k` token budget.++### Opt-in surfaces (excluded from `default-members`)++- **`forma-wasm`**: Compiles `forma-lang` and `forma-core` to `wasm32-unknown-unknown` using `[profile.wasm-release]` (`opt-level = "z"`, full LTO, single codegen unit, stripped symbols, plus optional `wasm-opt -Oz`). The zero-dependency npm package `forma-3d` wraps this module across three conditional entry points: `lib/workerd.mjs` (zero-boilerplate Cloudflare Workers), `lib/edge.mjs` (pure Web-standard Edge/browser loader with automatic trap-recovery cache eviction), and `lib/index.mjs` (Node.js/Bun/Deno with lazy local file loading).+- **`forma-server`**: A zero-dependency, multi-threaded HTTP/1.1 worker microservice built with `[profile.static-release]` (`lto = true`, `codegen-units = 1`, `strip = "symbols"`, `panic = "unwind"` preserved for per-request `catch_unwind`). While `Scene::new()` defaults to `allow_fs_import = true` and `max_statements = 4,096` for local CLI use, `forma-server` hardens every request with `allow_fs_import = false`, `max_statements = 1,024`, a `16 MiB` request cap, a bounded worker queue (`workers * 8`), and 15-second socket timeouts.++## Inside the transactional kernel++Every script evaluation flows through the same deterministic lifecycle inside `forma-lang` and `forma-core`:++```mermaid+flowchart LR+ P["Pipe / DSL Script"] --> PARSE["forma-lang Parser + GBNF"]+ PARSE --> SNAP["Scene: Push O(1) Arc CoW Snapshot"]+ SNAP --> EXEC["PolyMesh Ops & BVH CSG"]+ EXEC --> GATE{"MeshInvariants Gate (WT=ok, NM=0)"}+ GATE -- "strict fail / error" --> RB["Auto-Rollback (Restore Arc + Unit)"]+ RB --> SNAP+ GATE -- "pass" --> OBS["~100-tok Spatial Diff"]+ GATE -- "export" --> EXP["Unit-Aware GLB / STEP / 3MF / PNG / SVG"]+```++1. **Parsing**: `forma-lang` parses either `Forma-Pipe` or `Forma-DSL` into operations against a `Scene`. Because the GBNF grammar is compiled directly into the crate, local LLM samplers and the parser stay aligned.+2. **Copy-on-write snapshotting**: Before executing statements, `Scene` pushes a lightweight `SceneSnapshot` onto its undo stack. Because every named part is held in a `BTreeMap<String, Arc<PolyMesh>>`, snapshotting shares immutable mesh buffers in `O(1)` time without copying vertex or face arrays. The snapshot also records `op_counter`, `last_modified`, and the active `Unit`.+3. **Polyhedral execution**: Operations create a new `PolyMesh` for the mutated part and replace only its `Arc<PolyMesh>` entry in the map while unmodified parts stay shared across snapshots, applying double-precision geometric transformations or BVH-localized booleans and propagating semantic face tags (`top`, `bottom`, `hole`, `bevel`, `side`).+4. **Post-evaluation invariant gate**: `MeshInvariants::compute` performs a single-pass half-edge sort and Union-Find component analysis to verify watertightness, non-manifold edge count, boundary edges, winding consistency, finite vertices, degenerate face count, signed volume, surface area, and compactness.+5. **Commit or automatic rollback**: If an operator errors or strict mode rejects any invariant, `Scene` pops the pre-evaluation snapshot and restores both geometry and unit state cleanly. Otherwise, it computes a concise delta against the previous state and returns the `~100`-token observation text alongside structured invariants.++## Progressive disclosure in the MCP agent loop++The MCP surface decouples everyday modeling from specialized geometry domains so coding agents do not pay prompt-token overhead for operators they rarely use:++```mermaid+flowchart LR+ AGENT["Coding Agent"] --> EVAL["eval(code, strict=true)"]+ AGENT --> INSP["inspect(topic?)"]+ AGENT --> TX["tx(checkpoint | rollback | undo | reset)"]+ INSP -. "0-tok preload" .-> TIER1["Tier-1 Topics (deform, curves, uv, remesh, scene)"]+ EVAL --> STATE["In-Memory Scene (Arc CoW)"]+ INSP --> STATE+ TX --> STATE+ STATE --> EXP["export(path, scene?) -> GLB / STEP / 3MF / PNG / SVG"]+```++- The base tool catalog (`eval`, `inspect`, `tx`, `export`) carries only the compact `Forma-Pipe` core grammar inside `eval`'s description (`789` `o200k` tokens total).+- Specialized Tier-1 capabilities (deformers and solidify, Bezier/NURBS curves, LSCM UV unwrapping and QEM decimation, Surface Nets remeshing and bisect, and multi-object glTF scene graphs) remain compiled inside `forma-lang` at zero base-prompt cost and are fetched on demand through `inspect(topic)`.+- Explicit checkpoints (`tx` with `checkpoint`, `rollback`, `undo`, `reset`) complement per-evaluation auto-rollback, letting an agent branch a design safely before exporting meshes or 4-view visual renders.++## Unit-agnostic core with unit-aware boundaries++Internally, `forma-core` treats all coordinates as unitless `f64` model units in a right-handed Z-up frame. `Scene.unit` defaults to meters and travels alongside the geometry inside snapshots. Conversion happens strictly at export boundaries: `.3mf` and `.step` declare the active unit in file metadata, `.glb` scales vertices by `meters_per_unit()` and converts Z-up to glTF Y-up, and unitless formats (`.stl`, `.obj`) emit raw model coordinates.diff --git a/docs/explanation/why-forma.md b/docs/explanation/why-forma.mdnew file mode 100644index 0000000..d99688c--- /dev/null+++ b/docs/explanation/why-forma.md@@ -0,0 +1,46 @@+# Why Forma exists++Forma exists because desktop 3D suites and AI coding agents optimize for opposite constraints. Traditional CAD and DCC tools like Blender (`bpy`) assume a human is looking at a live GPU viewport, clicking faces with a mouse, and tolerating multi-hundred-megabyte installations. An autonomous agent operates headless, pays for every token in its context window, and has no visual feedback unless the engine hands back structured geometric truth.++## Why headless desktop 3D engines struggle under AI agents++When an agent drives a desktop engine through an imperative Python API like `bpy`, four structural failure modes appear repeatedly (documented empirically in the repository's [Phase 1 architecture audit](../PHASE1_ARCHITECTURE_AUDIT.md) and [Phase 1 baseline report](../PHASE1_BASELINE_REPORT.md)):++1. **Fragile integer topology indices**: Imperative mesh scripts select vertices, edges, and faces by numeric index (`faces[14]`). Any upstream boolean or subdivision renumbers every index, turning small edits into silent geometric corruption.+2. **Verbose imperative boilerplate**: Modeling a single flanged bracket in raw Python requires dozens of object-mode switches, modifier stack calls, bmesh updates, and transform cleanups. More tokens mean higher latency, higher cost, and more opportunities for syntax or state errors.+3. **Silent non-manifold failures**: A boolean operation can leave open boundary edges, inverted winding, zero-area faces, or non-manifold seams without raising an exception. Downstream slicers or game engines only discover the damage after the script finishes.+4. **Heavyweight deployment footprint**: Shipping a full desktop runtime (`>1 GB` installed) inside CI runners, edge workers, air-gapped sandboxes, or container microservices makes fast, deterministic 3D verification impractical.++## Four core design decisions in Forma++Forma addresses those failure modes at the kernel level rather than wrapping a desktop program in a thin adapter.++### Semantic selectors instead of integer indices++Every primitive and operation in `forma-core` preserves topological lineage and tags faces semantically (`top`, `bottom`, `front`, `back`, `left`, `right`, `hole`, `bevel`, `side`). Edge selectors such as `vertical`, `top_rim`, `outer_rim`, and `sharp` resolve dynamically against current geometry rather than hard-coded vertex numbers. An agent can bevel every vertical corner after five boolean cuts without knowing how many vertices the booleans created.++### Watertightness as a default invariant, not an afterthought++Forma represents solids as double-precision (`f64`) polyhedral meshes and runs a single-pass, sort-based topological check (`MeshInvariants`) after evaluation. By default, strict mode enforces closed watertightness (`boundary_edges == 0`), zero non-manifold edges, consistent half-edge winding, finite vertex coordinates, and non-degenerate volume compactness. When an edit breaks manifoldness, the kernel rejects it immediately instead of exporting broken geometry.++### Copy-on-write transactions for safe exploration++Exploratory modeling naturally involves failed booleans or overly aggressive bevels. Because `Scene` stores each named part behind an `Arc<PolyMesh>`, taking a snapshot before an evaluation or on an explicit checkpoint clones only smart pointers in `O(1)` time. If a script errors or fails strict verification, `Scene` restores both the previous mesh pointers and the previous length unit automatically, leaving prior valid work untouched.++### Compact textual observations over blind execution++Instead of returning silent success or forcing an agent to render and decode images on every intermediate step, Forma emits a compact observation channel (roughly `100` tokens) summarizing vertex/face counts, watertightness, non-manifold edge count, genus, volume, bounding box, semantic tag distribution, and the delta from the previous state. Visual PNG and SVG renders remain available when the caller wants spatial verification, while routine geometric checks stay cheap and deterministic.++## Why Forma enforces strict contributor budgets++Forma's [`CONTRIBUTING.md`](../../CONTRIBUTING.md) treats four constraints as non-negotiable architectural invariants rather than cosmetic targets:++- **Small binary footprint (`~1.3–1.8 MB` native, `~0.8 MB` WASM)**: Zero heavy C++ geometry kernels, no GPU driver stack, and no runtime dependencies in the npm package keep cold starts in milliseconds across laptops, edge workers, AWS Lambda, CI containers, and air-gapped VMs.+- **Sub-800-token MCP surface (`789` `o200k` tokens)**: Every tool schema attached to an MCP session consumes context on every turn of a conversation. Keeping the core MCP interface to four tools (`eval`, `inspect`, `tx`, `export`) and deferring niche operators behind on-demand `inspect(topic)` queries preserves context headroom for actual user tasks.+- **Strict manifoldness by default**: Opting out of watertightness requires an explicit choice rather than happening silently.+- **Opt-in crates for specialized surfaces**: Capabilities such as the HTTP microservice (`forma-server`), WebAssembly bindings (`forma-wasm`), and planned domain addons stay outside Cargo's `default-members` so users who only need the core CLI or MCP server never pay their compile-time or dependency cost.++## Further reading++- [Architecture](architecture.md) for how the six Rust crates, transactional kernel, and four runtime surfaces fit together.+- [Extended Benchmark Report](../EXTENDED_BENCHMARK_REPORT.md) and [Independent Automated Verification Report](../VERIFICATION_REPORT.md) for empirical measurements comparing Forma against headless `bpy`.diff --git a/docs/how-to/connect-ai-agents.md b/docs/how-to/connect-ai-agents.mdnew file mode 100644index 0000000..df29d8b--- /dev/null+++ b/docs/how-to/connect-ai-agents.md@@ -0,0 +1,104 @@+# How to connect AI agents (MCP, CLI, GBNF, and Sandboxes)++Use this guide to connect an AI coding agent, cloud VM, or local LLM to Forma over MCP, shell CLI, grammar-constrained decoding, or an air-gapped sandbox zip.++## Option A: Connect via MCP (recommended for interactive agents)++Forma exposes a stdio JSON-RPC 2.0 MCP server (`protocolVersion: "2024-11-05"`) with four tools (`eval`, `inspect`, `tx`, `export`) totaling `789` `o200k` tokens.++### Zero-install setup with npm (`forma-3d-mcp`)++Add the following entry to your MCP client configuration (`.mcp.json` for Claude Code, `.cursor/mcp.json` for Cursor, Antigravity `mcp_config.json`, or Codex MCP config):++```json+{+ "mcpServers": {+ "forma": {+ "command": "npx",+ "args": ["-y", "-p", "forma-3d", "forma-3d-mcp"]+ }+ }+}+```++### Native Rust binary setup (`forma-mcp`)++If you built the native workspace (`cargo build --release`), point the client at `target/release/forma-mcp` for lower startup latency and native `.blend` bridge support:++```json+{+ "mcpServers": {+ "forma": {+ "command": "/absolute/path/to/forma/target/release/forma-mcp"+ }+ }+}+```++### Verify the MCP server over stdio++Send an `initialize` and `tools/list` request to confirm the server responds with all four tools:++```bash+printf '%s\n%s\n' \+ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \+ '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' \+ | npx -y -p forma-3d forma-3d-mcp+```++Expected result: two JSON-RPC response lines where `id: 2` lists `eval`, `inspect`, `tx`, and `export`.++## Use checkpoints and progressive topic specs in an agent session++1. Call `tx` with `{"action": "checkpoint", "tag": "base"}` before attempting complex booleans or deformers.+2. Call `eval` with `{"code": "...", "strict": true}`. If any operation fails or violates watertightness (`WT!=ok`, `NM>0`, `NaN`, or degenerate volume), Forma automatically rolls back the scene and returns an error message without corrupting previous parts.+3. If an edit succeeds syntactically but does not match your design intent, revert to the named snapshot with `tx` (`{"action": "rollback", "tag": "base"}`) or step back one evaluation with `{"action": "undo"}`.+4. Load specialized operators on demand without bloating the base system prompt by calling `inspect` with a `topic` argument:+ - `{"topic": "deform"}`: `solidify`, `deform("bend"|"twist"|"taper"|"curve")`.+ - `{"topic": "curves"}`: `bezier`, `nurbs`, `extrude2d(..., holes=...)`.+ - `{"topic": "uv"}` (alias `"normals"`): `smooth`, `flat`, `unwrap`, `decimate`.+ - `{"topic": "remesh"}`: `remesh`, `bisect`, `load`.+ - `{"topic": "scene"}`: multi-node glTF scene export (`export(..., scene: true)`).+5. Export visual checks before finalizing: call `export` with `{"path": "preview.png", "size": 512}` or `{"path": "blueprint.svg"}`, then export the final asset (`{"path": "model.glb"}` or `{"path": "scene.glb", "scene": true}`).++## Option B: Drive Forma from a shell-capable agent or VM (`boat.dev`, E2B, Modal)++Agents with terminal access (Claude Code, Codex, `boat.dev`, E2B, Modal, Daytona) can use the drop-in [`SKILL.md`](../../SKILL.md) file directly with no MCP configuration:++1. Copy [`SKILL.md`](../../SKILL.md) into your agent's skill directory (or keep it at the repository root).+2. Instruct the agent to fetch the compiled language reference once with `npx forma-3d spec` (or `forma spec` natively) and run every script through `eval --strict`.+3. Inspect the exit code in automation: `0` means valid geometry, `3` means strict invariant failure (`WT!=ok` or `NM>0`).++## Option C: Air-gapped / no-network sandboxes (ChatGPT VM & Custom GPTs)++In offline containers without outbound internet (such as ChatGPT Code Interpreter), upload `forma-sandbox-linux-x86_64.zip` from GitHub Releases (contains static `musl` `forma`, zero-dep [`sandbox/forma.py`](../../sandbox/forma.py), and `SKILL.md`):++```python+import sys, zipfile+zipfile.ZipFile("/mnt/data/forma-sandbox-linux-x86_64.zip").extractall("/tmp/forma_kit")+sys.path.insert(0, "/tmp/forma_kit")+import forma++print(forma.eval_pipe(+ "flange = box(4, 2, 0.4) | cut(cyl(0.5, 1))",+ out="/mnt/data/flange.glb",+ render="/mnt/data/flange.png",+))+```++`sandbox/forma.py` automatically copies the binary out of `noexec` mounts (such as `/mnt/data`) to `/tmp/forma` with `chmod 0755`.++## Option D: Constrain local LLMs with the GBNF grammar++For `llama.cpp`, `vLLM`, or `XGrammar`, export the embedded `Forma-Pipe` grammar directly from the CLI:++```bash+npx forma-3d spec --gbnf > forma_pipe.gbnf+```++Pass `forma_pipe.gbnf` to your local sampler (for example `--grammar-file forma_pipe.gbnf` in `llama-cli` / `llama-server`) so the model emits syntactically valid `Forma-Pipe` statements on every generation.++## Related references++- [Reference: MCP, JS/TS, and HTTP APIs](../reference/apis.md)+- [Reference: Language, units, and formats](../reference/language-and-formats.md)diff --git a/docs/how-to/deploy-http-server.md b/docs/how-to/deploy-http-server.mdnew file mode 100644index 0000000..b5abbb5--- /dev/null+++ b/docs/how-to/deploy-http-server.md@@ -0,0 +1,127 @@+# How to deploy Forma (HTTP, Docker, Cloud, and Sandboxes)++Use this guide to run Forma as a headless HTTP microservice (`forma-server`), deploy the `FROM scratch` container to cloud providers (AWS, Cloudflare Containers, Google Cloud Run, Fly.io), or package static Linux `musl` binaries for AWS Lambda and air-gapped sandboxes.++`forma-server` is excluded from Cargo's `default-members` so core CLI/MCP builds stay minimal. It disables host filesystem access (`allow_fs_import = false`), caps script size (`max_statements = 1024`), enforces a `16 MiB` body limit, and processes jobs across a bounded worker pool.++## Option A: Build and run `forma-server` natively with Cargo++Build with `--profile static-release` (full LTO, single codegen unit, stripped symbols) or `--release`:++```bash+cargo build --profile static-release -p forma-server+./target/static-release/forma-server --bind 127.0.0.1:8080 --workers 4+```++You can also configure bind address and worker count through environment variables:++```bash+FORMA_BIND=0.0.0.0:8080 FORMA_WORKERS=4 ./target/static-release/forma-server+```++Verify the server is live:++```bash+curl -s http://127.0.0.1:8080/health+```++Expected response:++```json+{"status":"ok","version":"0.4.2","workers":4}+```++## Option B: Deploy the `FROM scratch` Docker image (AWS, Cloudflare, Cloud Run, Fly.io)++The repository [`Dockerfile`](../../Dockerfile) builds static `musl` binaries (`forma-server` and `forma` using `--profile static-release`) and copies them into `FROM scratch` (~2 MB final image) with `FORMA_BIND=0.0.0.0:8080` and port `8080` exposed:++```bash+docker build -t forma-server:0.4.2 .+docker run --rm -p 8080:8080 -e FORMA_WORKERS=4 forma-server:0.4.2+```++Because the container requires zero GPU and ~15 MB RAM, it deploys directly to **AWS ECS/Fargate/App Runner**, **Cloudflare Containers**, **Google Cloud Run**, **Azure Container Apps**, **Fly.io**, **Railway**, and **Render**.++## Option C: Static Linux binaries & offline sandboxes (AWS Lambda, ChatGPT VM)++GitHub Releases (`.github/workflows/server-release.yml`) publish static `+crt-static` Linux `musl` binaries for both **`x86_64`** and **`aarch64`** (AWS Lambda Graviton):++- `forma-linux-{x86_64,aarch64}-musl.tar.gz` — standalone `forma` CLI+- `forma-server-linux-{x86_64,aarch64}-musl.tar.gz` — standalone `forma-server` HTTP worker+- `forma-sandbox-linux-{x86_64,aarch64}.zip` — single-file offline kit (`forma` + [`sandbox/forma.py`](../../sandbox/forma.py) + `SKILL.md`)++For **AWS Lambda**:+- *Node.js runtime:* `npm install forma-3d` (architecture-independent WASM, fits a 128 MB Lambda).+- *Python runtime:* bundle `forma-sandbox-linux-{x86_64,aarch64}.zip` (or place `forma` in a Lambda Layer at `/opt/bin/forma`) and `import forma`.+- *Container / Custom runtime:* deploy `Dockerfile` with AWS Lambda Web Adapter (`AWS_LWA_PORT=8080`).++For **agent VMs (`boat.dev`, Modal, E2B, Daytona, Colab)**: run `npx -y forma-3d`, `cargo build --release`, or the static `musl` tarball directly.++## Evaluate a script and receive a binary mesh or render++Send `POST /v1/eval` with `format` set to `"glb"`, `"obj"`, `"stl"`, `"3mf"`, `"step"`, `"png"`, or `"svg"` to receive binary output plus `X-Forma-*` invariant headers:++```bash+curl -sS -D - http://127.0.0.1:8080/v1/eval \+ -H 'Content-Type: application/json' \+ -d '{+ "code": "p = box(40, 20, 6) | cut(cyl(5, 10)) | bevel(vertical, 1.5)",+ "unit": "mm",+ "strict": true,+ "format": "glb"+ }' \+ -o bracket.glb+```++Inspect the response headers for geometry telemetry:++- `X-Forma-Exec-Ms`: server-side execution time in milliseconds.+- `X-Forma-Watertight`: `true` or `false`.+- `X-Forma-NonManifold`: count of non-manifold edges.+- `X-Forma-Verts` / `X-Forma-Faces`: output vertex and face counts.++Set `"format": "json"` (the default) when you only need `ok`, `elapsed_ms`, observation `text`, and `parts` invariants.++## Pass external meshes safely without host disk access++Because `forma-server` sets `allow_fs_import = false`, `load("...")` only reads keys supplied in the request's `assets` base64 map:++```bash+MESH_B64=$(base64 -w0 input.glb)+curl -sS http://127.0.0.1:8080/v1/eval \+ -H 'Content-Type: application/json' \+ -d "{+ \"code\": \"p = load(\\\"input.glb\\\") | decimate(ratio=0.5)\",+ \"format\": \"glb\",+ \"assets\": { \"input.glb\": \"$MESH_B64\" }+ }" \+ -o lod.glb+```++For single-asset cleanup without writing a script, call `POST /v1/process`:++```bash+curl -sS http://127.0.0.1:8080/v1/process \+ -H 'Content-Type: application/json' \+ -d "{+ \"asset_base64\": \"$MESH_B64\",+ \"input_format\": \"glb\",+ \"output_format\": \"glb\",+ \"yup\": true,+ \"center_z0\": true,+ \"decimate\": 0.5+ }" \+ -o cleaned.glb+```++## Handle concurrency and backpressure in production++- Worker count defaults to `available_parallelism().clamp(1, 8)` and can be tuned up to `64` via `--workers` or `FORMA_WORKERS`.+- The request queue is bounded to `workers * 8` pending jobs. When saturated, `forma-server` immediately returns `503 Service Unavailable` with JSON error `"worker queue saturated"` so an upstream load balancer can shed load or retry.+- Do not send `Transfer-Encoding: chunked` requests; `forma-server` requires `Content-Length` and returns `501 Not Implemented` for chunked bodies.+- Place `forma-server` behind a TLS-terminating reverse proxy (such as Caddy, nginx, or Envoy) when exposing it beyond loopback.++## Related references++- [Reference: MCP, JS/TS, and HTTP APIs](../reference/apis.md)+- [Explanation: Architecture](../explanation/architecture.md)diff --git a/docs/how-to/embed-wasm-js.md b/docs/how-to/embed-wasm-js.mdnew file mode 100644index 0000000..0a72d0a--- /dev/null+++ b/docs/how-to/embed-wasm-js.md@@ -0,0 +1,146 @@+# How to embed forma-3d in JavaScript, Edge, and Browsers++Use this guide to evaluate `Forma-Pipe` scripts, manage stateful modeling sessions, and export meshes or renders inside Node.js (`>=18.0.0`), Bun, Deno, Cloudflare Workers, Vercel/Netlify Edge, Fastly Compute, or browsers using the zero-dependency `forma-3d` npm package.++## Install the package++```bash+npm install forma-3d+```++`forma-3d` has zero runtime dependencies and zero top-level `node:*` imports. Its `package.json` `exports` map automatically selects the right entry point per runtime:++| Runtime | Auto-selected entry | Notes |+| --- | --- | --- |+| **Cloudflare Workers (`workerd`)** | `lib/workerd.mjs` | Zero boilerplate; statically imports `../wasm/forma.wasm` for Wrangler's `CompiledWasm` rule. |+| **Vercel Edge / Netlify Edge / Fastly / Browsers** | `lib/edge.mjs` | Pure Web-standard loader with zero `node:*` references; accepts `WebAssembly.Module`, `Response`, `Uint8Array`, or URL. |+| **Node.js / Bun / Deno** | `lib/index.mjs` | Lazy local-file loader for bundled `wasm/forma.wasm`; zero top-level `node:*` imports. |++## Node.js / TypeScript one-shot usage++Use the top-level helpers when each request builds an independent part:++```js+import { writeFile } from "node:fs/promises";+import { evalPipe, exportMesh, renderPng, drawSvg } from "forma-3d";++const code = `+units("mm")+flange = box(80, 40, 8)+ | cut(cyl(10, 20))+ | bevel(vertical, 2.5)+ | mat("steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)+`;++const obs = await evalPipe(code, { strict: true });+console.log(obs.text);++const glb = await exportMesh(code, "glb", { strict: true });+const threemf = await exportMesh(code, "3mf", { strict: true });+const png = await renderPng(code, 512, { strict: true });+const svg = await drawSvg(code, { strict: true });++await Promise.all([+ writeFile("flange.glb", glb),+ writeFile("flange.3mf", threemf),+ writeFile("flange.png", png),+ writeFile("flange.svg", svg),+]);+```++Supported `exportMesh` formats are `"glb"`, `"step"`, `"stp"`, `"3mf"`, `"stl"`, `"obj"`, `"svg"`, and `"png"`.++## Cloudflare Workers (zero boilerplate)++No `nodejs_compat` flag or manual `.wasm` wiring is required. Wrangler resolves `forma-3d` through the `workerd` condition to `lib/workerd.mjs`:++```js+import { exportMesh } from "forma-3d";++export default {+ async fetch(req) {+ const glb = await exportMesh(await req.text(), "glb", { strict: true });+ return new Response(glb, { headers: { "content-type": "model/gltf-binary" } });+ },+};+```++If an isolate ever encounters a `WebAssembly.RuntimeError` (such as out-of-memory), `forma-3d` automatically evicts the poisoned WASM instance from its cache so the next request recovers cleanly on a fresh `WebAssembly.Instance`.++## Vercel Edge, Netlify Edge, Fastly, and Browsers++Import the `.wasm` asset using the `.wasm`-suffixed subpath (`forma-3d/forma.wasm`, matching edge bundler rules) or pass a `fetch()` `Response`:++```js+// Edge bundler (Vercel Edge / Netlify Edge / Fastly)+import formaWasm from "forma-3d/forma.wasm";+import { exportMesh } from "forma-3d";++const glb = await exportMesh("a = box(1, 1, 1)", "glb", { wasm: formaWasm, strict: true });+```++```js+// Browser / Web Worker (uses WebAssembly.instantiateStreaming when content-type is application/wasm)+import { loadForma } from "forma-3d/edge";++const engine = await loadForma(fetch("/forma.wasm"));+const session = engine.createSession();+try {+ session.eval("part = box(2, 2, 1) | bevel(vertical, 0.2)", { strict: true });+ const glb = session.exportBytes("glb");+} finally {+ session.free();+}+```++## Run multi-step edits with a stateful `FormaSession`++When your application applies iterative edits, maintains named checkpoints, or exports multi-part glTF scene graphs, load the WASM engine once with `loadForma()` and create a `FormaSession`:++```js+import { writeFile } from "node:fs/promises";+import { loadForma } from "forma-3d";++const engine = await loadForma();+const session = engine.createSession();++try {+ session.eval('base = box(4, 4, 0.4) | mat("base", color=(0.25, 0.28, 0.34))', { strict: true });+ session.tx("checkpoint", "after_base");++ session.eval('post = cyl(0.4, 2.0, z0=0.4) | mat("steel", color=(0.7, 0.72, 0.76), metallic=0.8)', {+ strict: true,+ });++ // Inspect structured invariants for a specific part+ const inv = session.invariants("post");+ console.log({ watertight: inv.watertight, nonManifold: inv.non_manifold_edges, volume: inv.volume });++ // Export all named parts as separate glTF 2.0 nodes+ const sceneGlb = session.exportSceneBytes();+ await writeFile("assembly.glb", sceneGlb);++ // Roll back to the saved checkpoint if needed+ session.tx("rollback", "after_base");+} finally {+ // Always release the WASM-side session handle+ session.free();+}+```++Always call `session.free()` inside a `finally` block to release memory allocated inside the WebAssembly instance. Pass `{ fresh: true }` to `loadForma(source, { fresh: true })` if you need an isolated `WebAssembly.Instance` rather than the cached instance.++## Query the compiled spec and GBNF grammar at runtime++```js+import { getSpec, getSpecTopic } from "forma-3d";++const pipeSpec = await getSpec({ dialect: "pipe" });+const gbnfGrammar = await getSpec({ gbnf: true });+const deformDocs = await getSpecTopic("deform");+```++## Related references++- [Reference: MCP, JS/TS, and HTTP APIs](../reference/apis.md)+- [Reference: CLI (forma and forma-3d)](../reference/cli.md)diff --git a/docs/how-to/units-and-mesh-processing.md b/docs/how-to/units-and-mesh-processing.mdnew file mode 100644index 0000000..127f633--- /dev/null+++ b/docs/how-to/units-and-mesh-processing.md@@ -0,0 +1,63 @@+# How to work with units and process existing meshes++Use this guide to author dimensionally accurate parts in millimeters or imperial units and to import, normalize, bisect, heal, or decimate existing 3D meshes.++## Declare model units inside your script (portable across all surfaces)++Forma geometry is unitless internally (`1.0` equals one model unit, defaulting to meters). Add `units("mm")` (or `m`, `cm`, `um`, `in`, `ft`) at the top of your `Forma-Pipe` script so the exact same script behaves identically across the native CLI, `forma-3d` WASM CLI, MCP server, JS/TS/Edge API, and `forma-server`:++```text+units("mm")+enclosure = box(100, 60, 25, z0=0)+ | bevel(vertical, 4)+ | shell(2.4, open_top=true)+```++If you use the native Rust CLI (`forma`) or `forma-server` (`POST /v1/eval`), you can also set the starting unit from outside the script:++```bash+forma eval --unit mm --out enclosure.3mf enclosure.forma+```++Note that `forma-3d` (the npm WASM CLI) does not expose a `--unit` CLI flag; use `units("mm")` inside the script when targeting WASM.++## Verify how each exporter handles your declared unit++- `.3mf`: embeds `model/@unit` (`millimeter`, `meter`, `centimeter`, `micron`, `inch`, or `foot`) so slicers open the part at true physical scale.+- `.step`: declares the model length unit inside the STEP AP214 header.+- `.glb`: automatically scales vertex positions by `unit.meters_per_unit()` because the glTF 2.0 specification requires meters (and converts Z-up to glTF Y-up).+- `.stl` and `.obj`: have no standard unit metadata field and are written in raw model units.++## Import, normalize, and decimate an existing mesh++Load an existing `.glb`, `.obj`, or `.stl` mesh with `load(...)`, inspect its invariants, and chain standard modeling or mesh-processing operators:++```text+part = load("scan.obj")+ | remesh(voxel_size=0.05)+ | decimate(ratio=0.5)+ | smooth(angle=35, weighted=true)+ | align_z0(0)+```++Evaluate and export with the CLI:++```bash+forma eval --strict --out clean.glb --render preview.png cleanup.forma+```++### Operator checklist for dirty or high-poly meshes++- **Heal open holes or multi-shell scans**: run `remesh(voxel_size=0.08)` (pure-Rust Surface Nets voxel remesh) to produce a watertight solid before downstream booleans.+- **Cut a flat base or split a model in half**: run `bisect(normal=(0, 0, 1), offset=0.0, clear_inner=false)` to slice cleanly with a watertight planar cap.+- **Reduce triangle count for real-time engines**: run `decimate(ratio=0.5)` or `decimate(faces=2000)` (Link-Condition QEM reduction that preserves `WT=ok NM=0`).+- **Generate clean UVs and shading normals**: run `unwrap(angle=45, margin=0.01)` followed by `smooth(angle=35, weighted=true)`.++## Normalize assets over HTTP without writing a script++If you run `forma-server`, use `POST /v1/process` to perform Y-up to Z-up conversion (`"yup": true`), uniform scaling (`"scale"`), resting on `z = 0` (`"center_z0": true`), and QEM decimation (`"decimate"` or `"target_faces"`) in a single request. See [How to deploy Forma](deploy-http-server.md).++## Related references++- [Reference: Language, units, and formats](../reference/language-and-formats.md)+- [Reference: CLI (forma and forma-3d)](../reference/cli.md)diff --git a/docs/reference/apis.md b/docs/reference/apis.mdnew file mode 100644index 0000000..d3f7544--- /dev/null+++ b/docs/reference/apis.md@@ -0,0 +1,112 @@+# MCP, JS/TS/Edge, and HTTP API reference++Exact interface contracts verified against `wrong-nebula/forma` `v0.4.2` (`crates/forma-mcp/src/main.rs`, `bin/forma-mcp.mjs`, `lib/edge.mjs`, `lib/workerd.mjs`, `lib/index.mjs`, `lib/index.d.ts`, and `crates/forma-server/src/main.rs`).++## MCP stdio JSON-RPC 2.0 API++- **Executables**: native `forma-mcp` (`crates/forma-mcp`) or npm WASM `forma-3d-mcp` / `forma-3d mcp` (`bin/forma-mcp.mjs`).+- **Transport**: newline-delimited JSON-RPC 2.0 over stdin/stdout.+- **Protocol version**: `"2024-11-05"`.+- **Server identity**: `{ "name": "forma-mcp", "version": "0.4.2" }`.+- **Supported methods**: `initialize`, `ping`, `tools/list`, `tools/call`.+- **Token footprint**: `789` `o200k` tokens across all 4 tool definitions (hard contributor ceiling `< 800`).++### MCP tools++| Tool | Arguments | Defaults / behavior |+| --- | --- | --- |+| `eval` | `{ code: string, strict?: boolean }` | `strict` defaults to `true`. Executes `Forma-Pipe` transactionally with auto-rollback on error or strict invariant failure. Embeds `SPEC_PIPE` in the tool description. |+| `inspect` | `{ topic?: "deform" \| "curves" \| "uv" \| "normals" \| "remesh" \| "scene" }` | With no `topic`, returns compact scene state, invariants, and tags. With `topic`, returns the compiled Tier-1 specification for that domain. |+| `tx` | `{ action: "checkpoint" \| "rollback" \| "undo" \| "reset", tag?: string }` | `tag` defaults to `"default"`. Mutates or restores O(1) `Arc<PolyMesh>` scene snapshots. |+| `export` | `{ path: string, part?: string, scene?: boolean, size?: integer }` | Writes `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, or `.png` (`size` defaults to `512`). When `scene: true`, exports all named parts as separate glTF 2.0 nodes. |++## JavaScript / TypeScript / Edge WASM API (`forma-3d`)++Zero runtime dependencies and zero top-level `node:*` imports.++### Package entry points (`package.json` `exports`)++| Import / Condition | Target | Behavior |+| --- | --- | --- |+| `"forma-3d"` (`workerd`) | `lib/workerd.mjs` | Zero-boilerplate Cloudflare Workers entry; statically imports `../wasm/forma.wasm`. |+| `"forma-3d"` (`edge-light`, `fastly`, `browser`) or `"forma-3d/edge"` | `lib/edge.mjs` | Pure Web-standard loader (zero `node:*` references); accepts `WebAssembly.Module`, `Response`, `Uint8Array`, or URL. |+| `"forma-3d"` (`node`, `default`) | `lib/index.mjs` | Universal entry with lazy local-file loader for Node.js (`>=18`), Bun, and Deno. |+| `"forma-3d/forma.wasm"` / `"forma-3d/wasm"` | `wasm/forma.wasm` | Prebuilt `wasm32-unknown-unknown` module (`lib/wasm.d.ts` typed as `WebAssembly.Module`). |++### Top-level functions++| Function | Signature | Return type |+| --- | --- | --- |+| `loadForma` | `loadForma(wasmSource?: WasmSource, opts?: LoadFormaOptions)` | `Promise<FormaEngine>` |+| `evalPipe` | `evalPipe(code: string, opts?: EvalOptions)` | `Promise<FormaObservation>` |+| `exportMesh` | `exportMesh(code: string, format?: "glb" \| "step" \| "stp" \| "3mf" \| "stl" \| "obj" \| "svg" \| "png", opts?: ExportOptions)` | `Promise<Uint8Array>` |+| `renderPng` | `renderPng(code: string, size?: number, opts?: EvalOptions)` | `Promise<Uint8Array>` |+| `drawSvg` | `drawSvg(code: string, opts?: EvalOptions)` | `Promise<string>` |+| `getSpec` | `getSpec(opts?: SpecOptions)` | `Promise<string>` |+| `getSpecTopic` | `getSpecTopic(topic: string, opts?: TopicOptions)` | `Promise<string>` |++### Exported TypeScript types (`lib/index.d.ts`)++- `WasmSource`: `WebAssembly.Module | WebAssembly.Instance | FormaEngine | ArrayBuffer | ArrayBufferView | Response | URL | string` (or a `Promise` resolving to any of those).+- `LoadFormaOptions`: `{ fresh?: boolean }` (`fresh: true` creates a new `WebAssembly.Instance` instead of reusing the cached engine).+- `EvalOptions`: `{ dialect?: "pipe" | "compact"; strict?: boolean; wasm?: WasmSource }` (`strict` defaults to `true`, `dialect` defaults to `"pipe"`).+- `ExportOptions extends EvalOptions`: adds `{ part?: string; size?: number }`.+- `SpecOptions`: `{ dialect?: "pipe" | "compact"; gbnf?: boolean; wasm?: WasmSource }`.+- `TopicOptions`: `{ wasm?: WasmSource }`.+- `FormaObservation`: `{ ok: boolean; elapsed_ms: number; text: string; parts: Record<string, unknown> }`.+- `FormaInvariants`: `{ verts: number; faces: number; watertight: boolean; non_manifold_edges: number; boundary_edges: number; genus: number; volume: number }`.++### `FormaEngine`, `FormaSession`, and isolate trap recovery++- `engine.spec(opts?: SpecOptions): string`: returns the compiled language specification or GBNF grammar.+- `engine.specTopic(topic: string): string`: returns the compiled Tier-1 specification for `"deform"`, `"curves"`, `"uv"` / `"normals"`, `"remesh"`, or `"scene"`.+- `engine.createSession(): FormaSession`: allocates a stateful WASM scene session.+- `session.eval(code: string, opts?: EvalOptions): FormaObservation`: evaluates code against the persistent scene.+- `session.inspect(): FormaObservation`: returns the current scene observation without mutating state.+- `session.tx(action: "checkpoint" | "rollback" | "undo" | "reset", tag?: string): string`: manages O(1) scene snapshots.+- `session.exportBytes(format, opts?: { part?: string; size?: number }): Uint8Array`: exports a single part or visual render.+- `session.exportSceneBytes(): Uint8Array`: exports all named parts as a multi-node `.glb` scene graph.+- `session.invariants(part?: string): FormaInvariants`: returns structured invariants for the specified or last-modified part.+- `session.free(): void`: releases the WASM-allocated session handle.+- **Trap recovery:** If any WASM call throws `WebAssembly.RuntimeError` (e.g. out-of-memory), `FormaEngine` automatically evicts itself from internal caches so subsequent calls instantiate a clean `WebAssembly.Instance`.++## `forma-server` HTTP/1.1 API (opt-in crate)++Binary built with `cargo build --profile static-release -p forma-server` (excluded from `default-members`).++### Configuration++| CLI flag | Environment variable | Default | Constraints |+| --- | --- | --- | --- |+| `--bind`, `-b` | `FORMA_BIND` | `127.0.0.1:8080` (`Dockerfile` sets `0.0.0.0:8080`) | TCP `host:port` bind address. |+| `--workers`, `-w` | `FORMA_WORKERS` | `available_parallelism().clamp(1, 8)` | Clamped to `1..=64`. |++### Routes++| Method and path | Request | Response |+| --- | --- | --- |+| `GET /health` | None | `200 OK` JSON: `{"status":"ok","version":"0.4.2","workers":N}` |+| `GET /spec` | Optional query `gbnf=1` or `dialect=compact` | `200 OK` `text/plain; charset=utf-8` |+| `POST /v1/eval` | JSON `{ code, strict?, dialect?, format?, size?, part?, unit?, assets? }` | `format="json"` (default) or `"text"` returns JSON + `X-Forma-Exec-Ms`; `glb`, `obj`, `stl`, `3mf`, `step`/`stp`, `png`, `svg` return binary + `X-Forma-*` headers. |+| `POST /v1/process` | JSON `{ asset_base64, input_format?, output_format?, size?, yup?, scale?, center_z0?, decimate?, target_faces?, unit? }` | Binary mesh/render (`output_format` defaults to `"glb"`) + `X-Forma-*` headers. |++### Binary response headers++- `X-Forma-Exec-Ms`: execution duration in milliseconds.+- `X-Forma-Watertight`: `true` or `false`.+- `X-Forma-NonManifold`: integer count of non-manifold edges.+- `X-Forma-Verts`: integer vertex count.+- `X-Forma-Faces`: integer face count.++### Hardcoded limits and error status codes++| Limit / guard | Value in `crates/forma-server/src/main.rs` | HTTP status on violation |+| --- | --- | --- |+| Host filesystem access | `scene.allow_fs_import = false` (assets via base64 only) | `422 Unprocessable Entity` |+| Max statements per request | `scene.max_statements = 1_024` | `422 Unprocessable Entity` |+| Max request body size | `MAX_BODY_BYTES = 16 MiB` (`16 * 1024 * 1024`) | `413 Payload Too Large` |+| Max header line / header count | `16 KiB` per line, `128` lines, `64` unique headers | `431 Request Header Fields Too Large` |+| Chunked request bodies | Rejected (`Content-Length` required) | `501 Not Implemented` |+| Worker queue capacity | `workers * 8` bounded `sync_channel` | `503 Service Unavailable` |+| Socket read/write timeouts | `15` seconds each | Connection closed |+| Worker panic recovery | `std::panic::catch_unwind` | `500 Internal Server Error` |diff --git a/docs/reference/cli.md b/docs/reference/cli.mdnew file mode 100644index 0000000..351e233--- /dev/null+++ b/docs/reference/cli.md@@ -0,0 +1,80 @@+# CLI reference (forma and forma-3d)++Forma ships two command-line executables backed by the same `forma-lang` and `forma-core` crates (`v0.4.2`):++- `forma`: native Rust binary compiled from `crates/forma-cli/src/main.rs`.+- `forma-3d` (alias `forma` inside the npm package): Node.js (`>=18.0.0`) WebAssembly wrapper at `bin/forma.mjs`.++## Subcommands++| Subcommand | Native `forma` | WASM `forma-3d` | Description |+| --- | --- | --- | --- |+| `eval` | Yes | Yes | Evaluate a script from a file path or stdin (`-` or omitted), print observation, and optionally export mesh, PNG, or SVG. |+| `render` | Yes | Yes | Evaluate a script and render a software PNG preview (`--out preview.png` required). |+| `draw` | Yes | Yes | Evaluate a script and generate a 3-view orthographic SVG blueprint (`--out blueprint.svg` required). |+| `spec` | Yes | Yes | Print the compiled `Forma-Pipe` or `Forma-DSL` specification, a progressive `--topic` spec, or the `--gbnf` grammar. |+| `mcp` | Separate binary (`forma-mcp`) | Yes (`forma-3d mcp` / `forma-3d-mcp`) | Start the stdio JSON-RPC 2.0 MCP server. |+| `version` / `--version` / `-V` | Yes | Yes | Print the CLI version string (`forma 0.4.2`). |+| `help` / `--help` / `-h` | Yes | Yes | Print usage summary. |++## `eval` options++| Flag | Default | Native `forma` | WASM `forma-3d` | Behavior |+| --- | --- | --- | --- | --- |+| `--dialect`, `-d <pipe\|compact>` | `pipe` | Yes | Yes | Select `Forma-Pipe` (`pipe`) or `Forma-DSL` (`compact`). |+| `--unit`, `-u <m\|cm\|mm\|um\|in\|ft>` | `m` | Yes | No | Set initial scene model unit before evaluating script. |+| `--strict` | Enabled | Yes | Yes | Enforce watertightness, zero non-manifold edges, finite vertices, and non-degenerate volume. |+| `--no-strict` | Disabled | Yes | Yes | Disable strict invariant rejection and exit code `3`. |+| `--json` | Disabled | Yes | Yes | Print full `Observation` JSON to stdout instead of compact text. |+| `--scene` | Disabled | Yes | Yes | Export all named parts as separate glTF 2.0 nodes when `--out` targets `.glb`. |+| `--out`, `-o <path>` | None | Yes | Yes | Export mesh (`.glb`, `.obj`, `.stl`, `.3mf`, `.step`, plus `.blend` on native only). |+| `--render <path.png>` | None | Yes | Yes | Render PNG preview alongside `eval`. |+| `--view <view>` | `quad` | Yes | No | Camera view for native `--render` / `render`: `quad`, `front`, `back`, `right`, `left`, `top`, `iso`. |+| `--size <px>` | `512` | Yes | Yes | Output PNG dimension in pixels (WASM `quad` renders 4-view preview at `size`). |+| `--draw <path.svg>` | None | Yes | Yes | Emit 3-view orthographic SVG engineering drawing. |+| `[file\|-]` | stdin | Yes | Yes | Script file path; reads stdin when omitted or `-`. |++## `render`, `draw`, and `spec` options++### `render`++- Native: `forma render [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--view quad|front|back|right|left|top|iso] [--size 512] --out preview.png [file|-]`+- WASM: `forma-3d render [--dialect pipe|compact] [--size 512] --out preview.png [file|-]`++### `draw`++- Native: `forma draw [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] --out blueprint.svg [file|-]`+- WASM: `forma-3d draw [--dialect pipe|compact] --out blueprint.svg [file|-]`++### `spec`++- Both CLIs: `spec [--dialect pipe|compact] [--topic <deform|curves|uv|normals|remesh|scene>] [--gbnf]`+- Native `forma spec` also accepts the topic as a positional argument (`forma spec deform`).++## Exit codes++| Code | Meaning |+| --- | --- |+| `0` | Evaluation and all requested exports/renders succeeded. |+| `1` | Script evaluation error, invariant rollback error, or file I/O error. |+| `2` | Invalid CLI argument, missing required flag value, or unknown subcommand. |+| `3` | Evaluation finished in `--strict` mode with `obs.ok == false` (for example `WT!=ok` or `NM>0`). |++## Environment variables++| Variable | Surface | Default | Effect |+| --- | --- | --- | --- |+| `BLENDER_BIN` | Native `forma` only | `/Applications/Blender.app/Contents/MacOS/Blender` | Path to stock Blender binary invoked when `--out` ends with `.blend`. |+| `FORMA_BIN` | `sandbox/forma.py` | Auto-discovered | Explicit path to static `forma` binary in air-gapped Python sandboxes. |++## Native vs WASM parity matrix++| Capability | Native `forma` | WASM `forma-3d` | Notes |+| --- | --- | --- | --- |+| `Forma-Pipe` and `Forma-DSL` evaluation | Yes | Yes | Identical `forma-lang` and `forma-core` code. |+| In-script `units("mm")` declaration | Yes | Yes | Portable across every runtime surface. |+| CLI `--unit` / `-u` flag | Yes | No | Use `units("...")` in the script on WASM. |+| CLI `--view` single-angle PNG flag | Yes | No | WASM always renders the 4-view `quad` PNG. |+| `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.png`, `.svg` | Yes | Yes | Identical exporters and software rasterizer. |+| `.blend` stock-Blender bridge export | Yes | No | Requires local Blender executable via `BLENDER_BIN`. |+| Built-in `mcp` subcommand | No (use `forma-mcp`) | Yes (`forma-3d mcp`) | Native builds separate `forma` and `forma-mcp` binaries. |diff --git a/docs/reference/language-and-formats.md b/docs/reference/language-and-formats.mdnew file mode 100644index 0000000..e88dadd--- /dev/null+++ b/docs/reference/language-and-formats.md@@ -0,0 +1,101 @@+# Language, units, and formats reference++Authoritative specification for Forma's two modeling dialects, semantic selectors, progressive topic extensions, unit system, and import/export formats (`v0.4.2`). For the exact live compiled prompt text, run `forma spec` or `npx forma-3d spec`.++## Coordinate system and evaluation rules++- **Axes**: Right-handed Z-up internally. `glTF` (`.glb`) export automatically converts to Y-up (`[x, z, -y]`).+- **Default unit**: `1.0` equals one meter (`Unit::Meter`) unless overridden by `units("...")`, native `--unit`, or HTTP `unit`.+- **Export target**: The last assigned or modified part exports by default unless a specific `part` or multi-node `scene` export is requested.+- **Transactional rollback**: Every `eval_script` call pushes an undo snapshot before execution and restores both geometry and `Scene.unit` if any statement fails or violates strict invariants.++## Dialects++| Dialect | CLI `--dialect` values | Structure | Formal grammar |+| --- | --- | --- | --- |+| `Forma-Pipe` (default) | `pipe`, `forma-pipe`, `a`, `default` | Expression pipeline: `name = prim \| op \| op` with multi-line `\|`, arithmetic (`+ - * / sqrt sin cos pi`), keyword arguments, and coordinate lists `at=[(x,y,z), ...]`. | `grammar/forma_pipe.gbnf` (`spec --gbnf`) |+| `Forma-DSL` (compact) | `compact`, `dsl`, `forma-dsl`, `b` | Line-oriented imperative statements (`new`, `add`, `sub`, `int`, `bev`, `shl`, `ext`, `ins`, `subdiv`, `mov`, `rot`, `scl`, `z0`, `mir`, `ckpt`, `rb`, `undo`, `units`). | Built-in EBNF (`spec --dialect compact`) |++## Core `Forma-Pipe` primitives++| Primitive | Signature | Notes |+| --- | --- | --- |+| `box` | `box(sx, sy, sz, at=, z0=)` | Centered at origin unless `at` or `z0` is given. |+| `cyl` | `cyl(r, h, segs=32, axis=z, at=, z0=)` | `segs=6` places vertices at `k * 60` degrees. |+| `cone` | `cone(r0, r1, h)` | Tapered frustum or cone when `r1=0`. |+| `sphere` | `sphere(r)` | Closed watertight UV/polyhedral sphere. |+| `torus` | `torus(R, r)` | Major radius `R`, minor tube radius `r`. |+| `revolve` | `revolve([(r, z), ...], segs=32)` | Lathe profile around Z; auto-closes to `r = 0`. |+| `arc_tube` | `arc_tube(center=(x, y, z), rx=, rz=, start=-90, end=90, r=0.08)` | Swept tube along an XZ elliptical arc (degrees). |+| `tube` | `tube([(x, y, z), ...], r=0.08)` | Circular tube along a 3D polyline or `bezier()`/`nurbs()` path. |+| `extrude2d` | `extrude2d([(x, y), ...], z0, z1, holes=)` | Watertight 2D polygon extrusion with optional inner hole loops. |+| `pipe` | `pipe(ro, ri, h)` | Hollow cylinder (outer radius `ro`, inner radius `ri`). |+| `loft` | `loft([(z, [(x, y), ...]), ...])` | Lofted solid between planar cross-sections at heights `z`. |+| `thread` | `thread(r0, r1, pitch, turns)` | Helical screw thread solid. |++## Core `Forma-Pipe` operators and queries++| Category | Operators |+| --- | --- |+| Booleans | `add(b, at=)`, `cut(b, at=)`, `intersect(b)` (`at` accepts `(x,y,z)` or `[(x,y,z), ...]`) |+| Patterns and symmetry | `mirror(x\|y\|z)`, `array(n, step)`, `radial(n, r=, axis=z)` |+| Topology modifiers | `shell(t, open_top=true)`, `subsurf(levels=1, crease=false)`, `bevel(edges, w, segs=1)`, `extrude(faces, d)`, `inset(faces, amt, depth=0)` |+| Transforms and placement | `move(x, y, z)`, `rot(rx, ry, rz)`, `scale(sx, sy, sz)`, `align(x\|y\|z, min\|center\|max, val)`, `on(base)`, `align_z0(z)` |+| Materials | `mat(name, color=(r, g, b), metallic=0.1, roughness=0.5)`, `color(r, g, b)` |+| Queries and units | `clearance(a, b)`, `section(part, z)`, `units("m\|cm\|mm\|um\|in\|ft")` |++## Semantic selectors++| Selector kind | Built-in selectors |+| --- | --- |+| Edge selectors (`bevel`) | `vertical`, `top_rim`, `bottom_rim`, `outer_rim`, `sharp`, `all` |+| Face selectors (`extrude`, `inset`) | `top`, `bottom`, `sides` |++## Progressive Tier-1 `spec_topic` domains++Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `getSpecTopic(name)`, or MCP `inspect({ topic })`.++| Topic | Aliases | Exposed operators / behavior |+| --- | --- | --- |+| `deform` | `deform` | `solidify(t, offset=-1.0, open_top=false)`, `deform("bend"\|"twist"\|"taper", axis=, angle=, factor=, subdivs=)`, `deform("curve", path=, axis=)` |+| `curves` | `curves` | `bezier([(x,y,z), ...], segs=24)`, `nurbs([(x,y,z), ...], degree=3, segs=32, weights=)`, `extrude2d(outer, z0, z1, holes=...)` |+| `uv` | `uv`, `normals` | `smooth(angle=35, weighted=true)`, `flat()`, `unwrap(angle=45, margin=0.01)`, `decimate(ratio=0.5, faces=)` |+| `remesh` | `remesh` | `remesh(voxel_size=0.08)`, `bisect(normal=(0,0,1), offset=0.0, clear_inner=false)`, `load("path.glb\|obj\|stl")` |+| `scene` | `scene` | Multi-object glTF 2.0 scene graph export (`--scene` in CLI, `scene: true` in MCP `export`, `exportSceneBytes()` in JS/TS). |++## Invariant metrics (`MeshInvariants`)++| Field | Observation key | Strict requirement |+| --- | --- | --- |+| `watertight` | `WT=ok` / `WT=OPEN` | Must be `true` (`boundary_edges == 0` and every undirected edge shared by 2 half-edges). |+| `non_manifold_edges` | `NM=0` | Must be `0`. |+| `boundary_edges` | `B=0` | Must be `0`. |+| `consistent_winding` | Included in `ok` | Opposite half-edge orientation across shared edges. |+| `nan_verts` | Included in `ok` | Must be `0` (all vertex coordinates finite). |+| `degenerate_faces` | Included in `ok` | Area below `1e-12` or fewer than 3 vertices. |+| `volume`, `surface_area` | `vol=...` | Positive volume; compactness `volume / surface_area^1.5 >= 1e-9` (`MIN_COMPACTNESS`). |+| `verts`, `faces`, `genus` | `V=`, `F=`, `g=` | Reported for every named part along with `bbox`, `size`, and `tags`. |++## Unit conversion table (`crates/forma-core/src/units.rs`)++| Symbol | Accepted aliases (case-insensitive) | Meters per unit | 3MF `model/@unit` |+| --- | --- | --- | --- |+| `um` | `micron`, `microns`, `micrometer`, `micrometers`, `micrometre`, `micrometres` | `1e-6` | `micron` |+| `mm` | `millimeter`, `millimeters`, `millimetre`, `millimetres` | `1e-3` | `millimeter` |+| `cm` | `centimeter`, `centimeters`, `centimetre`, `centimetres` | `1e-2` | `centimeter` |+| `m` (default) | `meter`, `meters`, `metre`, `metres` | `1.0` | `meter` |+| `in` | `inch`, `inches` | `0.0254` | `inch` |+| `ft` | `foot`, `feet` | `0.3048` | `foot` |++## Export and import formats++| Format | Extension | Direction | Unit handling | Axis / notes |+| --- | --- | --- | --- | --- |+| Binary glTF 2.0 | `.glb` | Import + Export | Scaled to meters (`meters_per_unit()`) | Y-up conversion, PBR materials, triplanar or LSCM UVs; supports multi-node `--scene` / `scene: true`. |+| STEP AP214 | `.step`, `.stp` | Export | Declares model unit in header | Faceted B-Rep solid for CAD interoperability. |+| 3D Manufacturing Format | `.3mf` | Export | Declares `model/@unit` | Ready for modern 3D-printing slicers. |+| Binary STL | `.stl` | Import + Export | Raw model units (format has no unit field) | Triangulated mesh. |+| Wavefront OBJ | `.obj` | Import + Export | Raw model units (format has no unit field) | Polygons/triangles. |+| PNG preview | `.png` | Export | Scale-invariant framed view | Pure-Rust software rasterizer (4-view `quad` default; single views on native CLI). |+| SVG blueprint | `.svg` | Export | Dimensioned in model units | 3-view orthographic engineering drawing. |+| Blender file | `.blend` | Export (native CLI only) | Inherits via bridge | Invokes local Blender (`BLENDER_BIN`). |diff --git a/docs/tutorials/first-part.md b/docs/tutorials/first-part.mdnew file mode 100644index 0000000..3b6d182--- /dev/null+++ b/docs/tutorials/first-part.md@@ -0,0 +1,141 @@+# Build your first watertight 3D part++In this tutorial you will create a strictly watertight mounting bracket from scratch using the `forma-3d` WASM CLI, verify its manifold geometry, render a 4-view preview PNG and a 3-view SVG engineering blueprint, and export both a web-ready `.glb` and a millimeter-accurate `.3mf` file for 3D printing.++## Prerequisites++- Node.js `18.0.0` or newer (`node --version`).+- A terminal with an empty working directory. No Rust toolchain, GPU, or Blender installation is required.++Create a clean folder for this walkthrough:++```bash+mkdir forma-first-part && cd forma-first-part+```++Check that `npx forma-3d` runs cleanly:++```bash+npx -y forma-3d --version+```++You should see `forma 0.4.2`.++## Step 1: Create and verify a base plate++Start with a minimal `Forma-Pipe` script that defines a single rectangular plate measuring `4 x 2 x 0.4` units centered at the origin:++```bash+cat > bracket.forma <<'EOF'+bracket = box(4, 2, 0.4)+EOF+```++Evaluate the script with `forma-3d eval`:++```bash+npx forma-3d eval bracket.forma+```++Forma runs with strict manifold checking enabled by default and prints a compact observation:++```text+OK [7.81ms] parts=1+- bracket: V=8 F=6 WT=ok NM=0 B=0 g=0 vol=3.200 bbox=[-2.00,-1.00,-0.20]..[2.00,1.00,0.20] size=[4.00,2.00,0.40]+ tags: back(1) bottom(1) front(1) left(1) right(1) top(1)+diff: +bracket (vol=3.200)+```++Notice four fields in that line:++- `WT=ok`: the mesh is watertight (closed solid with zero holes).+- `NM=0`: zero non-manifold edges.+- `B=0`: zero open boundary edges.+- `tags`: Forma automatically tagged each semantic face (`top`, `bottom`, `front`, `back`, `left`, `right`).++## Step 2: Cut holes, bevel vertical edges, and inspect a cross-section++Now extend `bracket.forma` using pipeline stages (`|`) to drill a central bore (`r = 0.5`), drill four corner mounting holes (`r = 0.2`) using an `at=[...]` coordinate list, bevel the vertical edges, assign a brushed slate PBR material, and measure the `z = 0` cross-section:++```bash+cat > bracket.forma <<'EOF'+bracket = box(4, 2, 0.4)+ | cut(cyl(0.5, 1.0))+ | cut(cyl(0.2, 1.0), at=[(-1.4, -0.5, 0), (-1.4, 0.5, 0), (1.4, -0.5, 0), (1.4, 0.5, 0)])+ | bevel(vertical, 0.12)+ | mat("anodized_slate", color=(0.35, 0.48, 0.62), metallic=0.85, roughness=0.3)+section(bracket, 0.0)+EOF+```++Run `eval` and emit a `.glb` mesh, a 4-view shaded PNG preview, and a 3-view orthographic SVG drawing in a single command:++```bash+npx forma-3d eval bracket.forma \+ --out bracket.glb \+ --render bracket.png \+ --draw bracket.svg+```++Forma validates the resulting solid and prints the updated invariants plus the cross-section query:++```text+OK [189.23ms] parts=1+- bracket: V=336 F=520 WT=ok NM=0 B=0 g=5 vol=2.677 bbox=[-2.00,-1.00,-0.20]..[2.00,1.00,0.20] size=[4.00,2.00,0.40]+ tags: bevel(520) bottom(176) hole(160) side(8) top(176)+diff: +bracket (vol=2.677)+query: section(part, z=0.000): loops=6 area=6.6914 perim=19.8738 xy=[-2.000,-1.000]..[2.000,1.000] size=[4.000,2.000]+```++Confirm what just happened:++- The genus increased from `g=0` to `g=5` because the bracket now has five through-holes (one central bore plus four corner holes).+- `section(bracket, 0.0)` reports `loops=6` (one outer perimeter plus five inner hole boundaries) and exact cross-sectional area `6.6914`.+- `WT=ok NM=0 B=0` proves the booleans and bevels produced a clean solid.++Verify that all three output files exist on disk:++```bash+ls -lh bracket.glb bracket.png bracket.svg+```++Open `bracket.png` to inspect the 4-view preview (isometric, front, right, top) and `bracket.svg` to inspect the dimensioned orthographic blueprint.++## Step 3: Export a millimeter-accurate 3MF file for 3D printing++By default, Forma coordinates are in meters. When you author a physical part for a slicer, declare `units("mm")` at the top of the script and write dimensions directly in millimeters:++```bash+cat > bracket-mm.forma <<'EOF'+units("mm")+bracket = box(80, 40, 8)+ | cut(cyl(10, 20))+ | cut(cyl(3.2, 20), at=[(-30, -12, 0), (-30, 12, 0), (30, -12, 0), (30, 12, 0)])+ | bevel(vertical, 2.5)+EOF+```++Evaluate and export directly to `.3mf`:++```bash+npx forma-3d eval bracket-mm.forma --out bracket-mm.3mf+```++Forma confirms `unit=mm` in the header and embeds `unit="millimeter"` inside the `.3mf` package:++```text+OK [65.88ms] parts=1 unit=mm+- bracket: V=336 F=520 WT=ok NM=0 B=0 g=5 vol=21980.009 bbox=[-40.00,-20.00,-4.00]..[40.00,20.00,4.00] size=[80.00,40.00,8.00]+ tags: bevel(520) bottom(176) hole(160) side(8) top(176)+diff: +bracket (vol=21980.009)+```++## What you achieved++You created a verified, strictly watertight 3D part with five through-holes and beveled edges, checked its cross-section mathematically, rendered both a 4-view PNG and an SVG blueprint, and exported `.glb` and millimeter `.3mf` deliverables using only `npx forma-3d`.++## Next steps++- Connect your coding agent to Forma over MCP: [How to connect AI agents](../how-to/connect-ai-agents.md).+- Embed Forma inside Node.js, Cloudflare Workers, Edge, or browsers: [How to embed forma-3d](../how-to/embed-wasm-js.md).+- Read how Forma's transactional rollback and invariants work: [Explanation: Architecture](../explanation/architecture.md).diff --git a/llms.txt b/llms.txtindex b5458d9..829ec1b 100644--- a/llms.txt+++ b/llms.txt@@ -14,6 +14,10 @@- [crates/forma-mcp](crates/forma-mcp): `forma-mcp` stdio JSON-RPC 2.0 MCP server (4 tools, 789 o200k tokens)- [crates/forma-server](crates/forma-server): Zero-dependency multi-threaded HTTP/1.1 headless microservice (`/health`, `/spec`, `/v1/eval`, `/v1/process`) + `Dockerfile`- [crates/forma-wasm](crates/forma-wasm): Zero-dependency WebAssembly core (`wasm/forma.wasm`, powers `forma-3d` on npm)+- [lib/edge.mjs](lib/edge.mjs): Pure Web-standard WASM API with zero `node:*` imports and automatic trap-recovery eviction (browsers, Vercel/Netlify Edge, Deno Deploy, Supabase Edge Functions, Fastly Compute)+- [lib/workerd.mjs](lib/workerd.mjs): Zero-boilerplate Cloudflare Workers entry (`workerd` condition, statically imports `../wasm/forma.wasm`)+- [sandbox/forma.py](sandbox/forma.py): Zero-dependency Python wrapper for air-gapped sandboxes (ChatGPT VM / Code Interpreter, AWS Lambda Python layers, Colab, Modal); auto-handles `noexec` mounts+- [docs/README.md](docs/README.md): Diataxis onboarding hub ([tutorial](docs/tutorials/first-part.md), [how-to guides](docs/how-to/embed-wasm-js.md), [CLI/API/format references](docs/reference/apis.md), [why Forma & architecture](docs/explanation/architecture.md))- [docs/VERIFICATION_REPORT.md](docs/VERIFICATION_REPORT.md): Independent geometric, slicer, Blender import, fuzz, and MCP verification- [docs/EXTENDED_BENCHMARK_REPORT.md](docs/EXTENDED_BENCHMARK_REPORT.md): Full 12-model / 10-lab cross-lab & reasoning-effort scaling study@@ -62,6 +66,13 @@ cargo build --release- `clearance(part_a, part_b)` — exact 3D minimum surface distance & collision check- `section(part, z)` — exact 2D cross-section loop count, area, perimeter, XY bounds+## Supported Runtimes & Deployment Targets++- **Edge & Browsers (zero `node:*` imports):** Cloudflare Workers (zero boilerplate — `workerd` condition auto-imports `forma.wasm` via `lib/workerd.mjs`), Vercel Edge / Netlify Edge / Fastly (`import wasm from "forma-3d/forma.wasm"; await exportMesh(code, "glb", { wasm })`), Deno Deploy, Supabase Edge Functions, and browsers/Web Workers (`loadForma(fetch("/forma.wasm"))`).+- **Cloud & Serverless:** AWS Lambda (`x86_64` & `aarch64` via `forma-3d` Node runtime, static `musl` binary, or Lambda Layer with `sandbox/forma.py`), AWS ECS/Fargate/App Runner, Cloudflare Containers, Google Cloud Run, Fly.io, Azure Container Apps, Railway, Render (via ~2 MB `FROM scratch` `Dockerfile`).+- **Agent VMs & Notebooks:** `boat.dev`, Modal, E2B, Daytona, Google Colab, Kaggle, Codespaces (`npx -y forma-3d` or native binary).+- **No-Network Sandboxes (ChatGPT VM / Custom GPTs, air-gapped containers):** Upload `forma-sandbox-linux-x86_64.zip` from GitHub Releases (static `x86_64-unknown-linux-musl` `forma` binary + `sandbox/forma.py` + `SKILL.md`).+## MCP Tools (`forma-mcp`, 789 o200k tokens total)1. `eval({ code, strict? })` — Run transactional Forma-Pipe code (auto-rollback on error); returns compact ~100-token diff (`V`, `F`, `WT`, `NM`, `B`, `g` genus, `vol`, `bbox`, `size`, tags, query results).