Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

docs: streamline agent guides, sync CLI/MCP/language references, and clean up launch notes

wrong-nebulaf68aad7fdcda
diff --git a/AGENTS.md b/AGENTS.md
index cd8d162..02bc85b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,7 @@ Forma is a ~1.7 MB native (~0.8 MB WASM) pure-Rust headless 3D polyhedral modeli
## 1. Connect via MCP (`forma-mcp`) — Recommended
-`forma-mcp` is a stateful stdio JSON-RPC 2.0 server with **4 tools** totaling **789 `o200k` tokens** (including the full `Forma-Pipe` syntax spec).
+`forma-mcp` is a stateful stdio JSON-RPC 2.0 server with **4 tools** totaling **721 `o200k` tokens** (including the full `Forma-Pipe` syntax spec).
Build the binary once:
```bash
@@ -30,10 +30,10 @@ Add to your MCP client config (Claude Code, Cursor, Codex, Antigravity, etc.)
### Exposed Tools
| Tool | Purpose |
|---|---|
-| `eval` | Execute transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result); returns a ~100-token spatial diff (`WT`, `NM`, `g` genus, `vol`, `bbox`, `size`, tags). |
-| `inspect` | Inspect current scene invariants and bounding boxes without mutating state. |
-| `tx` | O(1) copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset`. |
-| `export` | Export to `.glb` (glTF 2.0 Y-up, PBR + UVs), faceted `.step` (planar faces), `.3mf`, `.stl`, `.obj`, or render a zero-GPU 4-view studio `.png` preview (`~20–75 KB`). |
+| `eval` | Execute transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result); scalar variables persist across `eval` calls; returns a ~100-token spatial diff (`WT`, `NM`, `g` genus, `vol`, `bbox`, `size`, tags). |
+| `inspect` | Inspect current scene invariants and bounding boxes without mutating state (or pass `topic` for progressive specs: `deform`, `curves`, `uv`, `remesh`, `scene`). |
+| `tx` | O(1) copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset` (rolls back both geometry and scalar variables). |
+| `export` | Export to `.glb` (glTF 2.0 Y-up, PBR + UVs), faceted `.step` (planar faces), `.3mf`, `.stl`, `.obj`, `.svg` blueprint, `.blend` (via Blender bridge), or render a zero-GPU 4-view studio `.png` preview (`~20–75 KB`). Pass `scene: true` to export/render all named parts together (`.glb`, `.blend`, `.png`, `.svg`). |
---
@@ -42,7 +42,7 @@ Add to your MCP client config (Claude Code, Cursor, Codex, Antigravity, etc.)
If your agent already has a shell tool, you don't even need MCP—pipe scripts directly into `forma`:
```bash
-# 1. Read the compact zero-shot language spec (~355 tokens)
+# 1. Read the compact zero-shot language spec (~485 o200k tokens)
forma spec
# 2. Build, verify watertightness, export CAD/mesh, and render a 4-view preview in ~15 ms
@@ -66,15 +66,12 @@ query: section(part, z=0.000): loops=6 area=6.4393 perim=21.4096 xy=[-2.000,-1.0
---
-## 3. Recommended Agent Loop
+## 3. Token-Efficient Agent Loop
-1. **Draft in `Forma-Pipe`**: Use semantic selectors (`vertical`, `top_rim`, `bottom_rim`, `outer_rim`, `top`, `sides`) and relational placement (`z0=0`, `| on(base)`, `| align(z, min, 0)`) instead of manual vertex/offset math.
-2. **Verify Invariants Immediately**: Check `WT=ok NM=0 B=0`, bounding box `size=[x,y,z]`, volume `vol`, and Euler genus `g` (e.g., `g=1` confirms a mug handle or bore is open; `g=5` confirms 5 through-holes).
-3. **Run Geometric Checks When Assembling Parts**:
- - `clearance(part_a, part_b)` verifies exact minimum surface distance and catches collisions.
- - `section(part, z)` verifies cross-section loop count and wall area at any height `z`.
-4. **Optional Visual Check for VLMs**: Render a 4-view (`Front / Right / Top / Iso`) studio preview via `--render preview.png` or `export(path="preview.png")` in ~4 ms with zero GPU, then inspect the image.
-5. **Safe Exploration**: Use `tx(action="checkpoint", tag="v1")` before risky boolean/bevel steps and `tx(action="rollback", tag="v1")` on error.
+1. **Batch Into 1–2 `eval` Calls**: Write the complete part or assembly parametrically instead of issuing one tool call per primitive. Use persistent scalars, `def name(p1, p2=default) = expr` macros, `[expr for i in range(n)]` list comprehensions, `gear(teeth, module=, h=, pressure_angle=20, bore=0)`, and `tan`/`atan`/`atan2`. Prefix temporary cutters/helpers with `_` (`_tmp = ...`) so they stay local and do not pollute `scene.parts` or `scene: true` exports; use `del("name")` to remove stale parts.
+2. **Verify Invariants From the Spatial Diff**: Check `WT=ok NM=0 B=0`, bounding box `size=[x,y,z]`, volume `vol`, and Euler genus `g` (e.g., `g=1` confirms a mug handle or bore is open; `g=5` confirms 5 through-holes). Add `clearance(part_a, part_b)` or `section(part, z)` in the same `eval` when assembling parts.
+3. **Skip Routine Checkpoints**: `eval(strict=true)` automatically rolls back on any error or non-manifold result. Only call `tx(action="checkpoint", tag="v1")` before genuinely exploratory edits you might revert even if they succeed.
+4. **Preview Multi-Part Assemblies Once**: Render a 4-view (`Front / Right / Top / Iso`) studio preview once at the end (or when debugging complex spatial fit) via `export(path="preview.png", scene=true)` (or CLI `--scene --render preview.png`) in ~4 ms with zero GPU. `scene: true` renders all named scene parts together with their materials — do not boolean-merge a dummy assembly just to preview.
---
@@ -92,6 +89,7 @@ forma spec --gbnf > forma_pipe.gbnf
## 5. Common Pitfalls & Best Practices
- **Cutting through-holes cleanly:** Make cutting cylinders slightly taller than the target plate (e.g., `cyl(0.5, 1.0)` for a `0.4` thick plate) to avoid grazing coplanar caps.
-- **Multi-hole patterns:** Pass `at=[(x1,y1,z1), (x2,y2,z2), ...]` in a single `| cut(...)` or `| add(...)` call—Forma automatically batches pairwise-disjoint booleans in one pass.
+- **Multi-hole patterns:** Pass `at=[(x1,y1,z1), ...]` or a list comprehension `at=[(r*cos(2*pi*i/n), r*sin(2*pi*i/n), 0) for i in range(n)]` in a single `| cut(...)` or `| add(...)` call—Forma automatically batches pairwise-disjoint booleans in one pass.
+- **Meshing spur gears:** `gear(z, module=m, h=h, bore=...)` places tooth 0 on `+X`; position a mating gear at center distance `m * (z1 + z2) / 2` and rotate it around Z by `180 / z2` degrees when `z2` is even (`0` degrees when `z2` is odd).
- **Sharp revolved/mechanical subsurf:** Use `subsurf(1, crease=true)` if you want smooth curvature without shrinking sharp rims.
-- **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (glTF 2.0 Y-up, PBR materials + LSCM/triplanar UVs), faceted `.step` (watertight planar-face ISO 10303-21 solid; no analytic cylinders/NURBS) for reference/assembly import into SolidWorks/Fusion 360/FreeCAD, `.3mf`/`.stl` for 3D printing (model in mm? start the script with `units("mm")` so `.3mf`/`.step` declare millimetres; `.stl`/`.obj` have no unit field and keep model units), `.svg` for dimensioned blueprints, and `.blend` via Blender bridge.
+- **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (glTF 2.0 Y-up, PBR materials + LSCM/triplanar UVs; pass `scene: true` for multi-part scenes), faceted `.step` (watertight planar-face ISO 10303-21 solid; no analytic cylinders/NURBS) for reference/assembly import into SolidWorks/Fusion 360/FreeCAD, `.3mf`/`.stl` for 3D printing (model in mm? start the script with `units("mm")` so `.3mf`/`.step` declare millimetres; `.stl`/`.obj` have no unit field and keep model units), `.svg` for dimensioned blueprints (supports `scene: true`), and `.blend` via Blender bridge.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 618ac8f..97326d9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -25,7 +25,7 @@ Optional crates (excluded from `default-members`): `cargo build --release -p for
## Four Rules to Keep in Mind
1. **Keep core tiny:** Core `forma` stays ~1.7–1.8 MB native / ~0.8 MB WASM (pure Rust, minimal deps).
-2. **Keep MCP compact:** Core `forma-mcp` stays under **800 `o200k` tokens** (currently 789).
+2. **Keep MCP compact:** Core `forma-mcp` stays under **800 `o200k` tokens** (currently 723).
3. **Strict watertightness by default:** `--strict` must reject non-manifold, open-boundary, inverted-winding, `NaN`, or zero-volume results and roll back cleanly.
4. **Domain pipelines live in opt-in crates:** Big domain workflows (3D printing, UE5, etc.) go in their own workspace crate excluded from `default-members` (`0` bytes / `0` tokens added to core). Rigging, animation, map baking, and full PBR/EEVEE-class rendering are separate companion apps, not part of core Forma.
diff --git a/README.md b/README.md
index a969062..506f0a6 100644
--- a/README.md
+++ b/README.md
@@ -12,10 +12,10 @@ Forma replaces headless Blender's 3D mesh modeling, boolean, and studio-preview
|---|---:|---:|---:|
| **Cold-Start Eval + GLB Export** | 1,306.8 ms | **16.9 ms** (`5.4 ms` batch flange) | **~77×–89× faster** |
| **Completion Tokens (12-model avg)** | 294,661 total | **84,551 total** | **3.49× fewer** (up to **15.5×**) |
-| **Pass Rate (12 models / 10 labs)** | 79.1% (`bpy`) | **95.5% – 100%** | **+16.4 pp** |
+| **Pass Rate (12 models / 9 labs)** | 79.1% (`bpy`) | **95.5% – 100%** | **+16.4 pp** |
| **Binary / Install Footprint** | 953 MB | **~1.7–1.8 MB** native (**~0.8 MB** WASM) | **~530× smaller** |
| **Peak Memory RSS** | 223 MB | **~6–14 MB** (`6.1 MB` macOS / `13.5 MB` Linux) | **~16×–36× less RAM** |
-| **MCP Tool Schema Budget** | — | **789 `o200k` tokens** (4 tools) | Strictly `< 800` |
+| **MCP Tool Schema Budget** | — | **723 `o200k` tokens** (4 tools) | Strictly `< 800` |
---
@@ -70,7 +70,7 @@ Forma is designed for drop-in agent use via **MCP**, **CLI**, **Agent Skills**,
### MCP Server Setup (`forma-mcp` / `npx -p forma-3d forma-3d-mcp`)
-Add Forma's MCP server (4 tools: `eval`, `inspect`, `tx`, `export` — **789 `o200k` tokens** total) to any MCP client:
+Add Forma's MCP server (4 tools: `eval`, `inspect`, `tx`, `export` — **723 `o200k` tokens** total) to any MCP client:
```json
{
@@ -85,7 +85,7 @@ Add Forma's MCP server (4 tools: `eval`, `inspect`, `tx`, `export` — **789 `o2
Or invoke directly from any shell-capable agent:
```bash
-forma spec # ~355-token language reference
+forma spec # ~485-token language reference
forma eval --strict --out out.glb script.forma # transactional eval + ~100-tok spatial diff
forma render --out preview.png script.forma # 4-view studio PNG (~4 ms, zero GPU)
forma draw --out blueprint.svg script.forma # dimensioned vector engineering blueprint
@@ -122,7 +122,7 @@ Because `wasm/forma.wasm` is a **~0.8 MB zero-import WebAssembly module** (zero
| 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`) |
+| **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 `< 5 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`) |
@@ -198,7 +198,7 @@ All models were evaluated head-to-head on stock headless **Blender 5.3.0 (`bpy`)
<img src="assets/readme_benchmarks.png" alt="12-Model Benchmark Results: Forma vs Stock Blender 5.3" width="100%" />
</p>
-### 1. Cross-Lab Results — 12 Models Across 10 Labs (`low` reasoning)
+### 1. Cross-Lab Results — 12 Models Across 9 Labs (`low` reasoning)
| Model | `bpy` Pass (P@1 / P@3) | **Forma Pass (P@1 / P@3)** | `bpy` Tokens (API / Comp) | **Forma Tokens (API / Comp)** | `bpy` Mean IoU | **Forma Mean IoU** | Comp Token Reduction |
|---|---:|---:|---:|---:|---:|---:|---:|
diff --git a/SKILL.md b/SKILL.md
index 462721a..122139b 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,6 +1,6 @@
---
name: forma
-description: Create, modify, inspect, render, and export watertight 3D polyhedral models in milliseconds using Forma (a ~1.7 MB native / ~0.8 MB WASM pure-Rust headless 3D modeling engine). Use whenever a task involves 3D mesh/CAD generation, mechanical parts, enclosures, brackets, threads, lofts, pipes, booleans, .glb/faceted .step/.3mf/.stl/.obj/.blend export, 4-view .png studio previews, or dimensioned .svg engineering blueprints.
+description: Create, modify, inspect, render, and export watertight 3D polyhedral models in milliseconds using Forma (a ~1.7 MB native / ~0.8 MB WASM pure-Rust headless 3D modeling engine). Use whenever a task involves 3D mesh/CAD generation, mechanical parts, gears, enclosures, brackets, threads, lofts, pipes, booleans, .glb/faceted .step/.3mf/.stl/.obj/.blend export, 4-view .png studio previews, or dimensioned .svg engineering blueprints.
---
# Forma — Headless 3D Modeling Skill
@@ -21,19 +21,19 @@ Connect `forma-mcp` (native binary) or `npx -y -p forma-3d forma-3d-mcp` (zero-i
}
}
```
-Exposed tools (4 tools, 789 `o200k` tokens total):
-- `eval` — Run transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result) and return a ~100-token spatial diff (`WT`, `NM`, `g`, `vol`, `bbox`, `size`, tags).
-- `inspect` — Read current scene invariants and bounding boxes without mutating state.
+Exposed tools (4 tools, 721 `o200k` tokens total):
+- `eval` — Run transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result) and return a ~100-token spatial diff (`WT`, `NM`, `g`, `vol`, `bbox`, `size`, tags). Scalar variables persist across `eval` calls (and roll back with `tx`).
+- `inspect` — Read current scene invariants and bounding boxes without mutating state (or pass `topic: "deform"|"curves"|"uv"|"remesh"|"scene"` for on-demand domain specs).
- `tx` — Instant copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset`.
-- `export` — Export to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.png` (4-view studio), or `.blend` (via optional Blender bridge).
+- `export` — Export to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.png` (4-view studio), or `.blend` (via local Blender bridge); pass `scene: true` to export/render **all named scene parts together** (`.glb`, `.blend`, `.png`, or `.svg`).
### Option B — CLI (single-shot Unix pipes)
Use either the compiled native binary (`forma`) or the cross-platform npm CLI (`npx -y forma-3d`):
```bash
-forma spec # Print ~355-token language reference
+forma spec # Print ~485-token language reference
forma spec --gbnf # Print GBNF grammar for constrained decoding
-forma eval --strict \
- --out part.glb \
+forma eval --strict --scene \
+ --out scene.glb \
--render preview.png \
--draw blueprint.svg <<'EOF'
...Forma-Pipe script...
@@ -42,19 +42,28 @@ EOF
---
-## 2. Standard 5-Step Modeling Workflow
+## 2. Token-Efficient Modeling Workflow
-1. **Plan coordinates (Z-up) and unit.** Numbers are unit-agnostic and default to meters; if you model in another unit (e.g. a Pi case in mm) declare it with `units("mm")` (or `forma eval --unit mm`) so `.3mf`/`.step` exports open at the right size (`.glb` is scaled to metres; `.stl`/`.obj` keep model units). Primitives are centered at `(0, 0, 0)` unless placed with `at=(x,y,z)` or `z0=Z` (sets bottom Z; if both `at=` and `z0=` are given, `z0=` overrides the Z coordinate after `at=` positions X/Y).
-2. **Checkpoint before risky ops (MCP).** Call `tx(action="checkpoint", tag="base")` before complex cuts/bevels so you can roll back in O(1).
-3. **Write declarative `Forma-Pipe`.** Chain operations with `|`. Intermediate named parts still appear in the spatial diff (`parts=N`), while the **last assigned variable** is exported by default (or pass `part` in MCP `export` to pick a specific part).
-4. **Always evaluate with `--strict` / `strict: true`.** Verify the returned spatial diff reports `WT=ok` and `NM=0`, plus exact `bbox` / `size` / `section` / `clearance`.
-5. **Visually inspect & export.** Render a 4-view `.png` (`--render preview.png`) to confirm proportions visually, then export `.glb` (PBR + triplanar UVs), `.step`, `.3mf`, `.stl`, `.obj`, `.blend` (native CLI with Blender installed), or `.svg` blueprint (`--draw blueprint.svg`).
+Minimize round-trips and output tokens by treating `Forma-Pipe` as a parametric script rather than stepping one primitive per turn:
+
+1. **Batch the whole part or assembly into 1–2 `eval` calls.** Define shared parameters as scalars (which persist across MCP `eval` calls), reuse geometry with `def name(p1, p2=default) = expr` macros and `[expr for i in range(n)]` comprehensions, and prefix temporary cutters/helpers with `_` (`_tmp = ...`) so they stay local and never pollute `scene.parts` or `scene: true` exports.
+2. **Set coordinates (Z-up) and unit upfront.** Numbers default to meters; for mm/in parts, start with `units("mm")` (or `forma eval --unit mm`) so `.3mf`/`.step` open at the right size (`.glb` scales to metres; `.stl`/`.obj` keep model units). Primitives center at `(0, 0, 0)` unless placed with `at=(x,y,z)` or `z0=Z` (`z0=` overrides Z if both are given).
+3. **Skip routine checkpoints.** `eval` with `strict: true` (default) already auto-rolls back on any error or watertightness failure (`WT!=ok`, `NM>0`). Only call `tx(action="checkpoint", tag="...")` before genuinely risky or exploratory edits you may want to discard even if they succeed.
+4. **Verify from the returned diff, then preview once.** Check `WT=ok NM=0`, `bbox`/`size`, `vol`, `genus`, and geometric queries (`clearance(a, b)`, `section(part, z)`) directly in the `eval` output. Call `export({ path: "preview.png", scene: true })` once at the end (or when debugging complex spatial fit) instead of re-rendering after every edit — `scene: true` renders all named parts together with their materials, so never boolean-merge a dummy assembly just to preview.
+5. **Clean up & export.** Remove unwanted parts with `del("name")`, then export `.glb`/`.blend` (with `scene: true` for multi-part assemblies), `.step`, `.3mf`, `.stl`, `.obj`, or `.svg`.
---
## 3. Forma-Pipe Language Reference
-- **Syntax:** `name = expr | op | op` (multi-line `|` supported; math `+ - * / sqrt sin cos asin acos abs pi`).
+- **Syntax:** `name = expr | op | op` (multi-line `|` supported).
+- **Parametric helpers:**
+ - Persistent scalars across MCP `eval` calls (`m = 2.0`, `h = 8.0`; rolled back by `tx`).
+ - Macros: `def name(p1, p2=default) = expr`
+ - List comprehensions: `[expr for i in range(n)]` (`range(stop)`, `range(start, stop)`, `range(start, stop, step)`).
+ - Local mesh helpers: `_tmp = ...` stays local to the script and is excluded from `scene.parts` and `scene: true` exports.
+ - Delete named part: `del("name")`.
+- **Math:** `+ - * / sqrt sin cos tan asin acos atan atan2 abs pi`.
- **Common primitive kwargs:** `at=(x,y,z)` or `at=[(x,y,z), ...]` (batch), `z0=Z`, `rot=(rx,ry,rz)`.
### Primitives
@@ -66,7 +75,8 @@ EOF
| `sphere(r)` | UV sphere |
| `torus(R, r)` | Major radius `R`, tube radius `r` |
| `pipe(ro, ri, h)` | Hollow cylindrical tube |
-| `extrude2d([(x,y), ...], z0, z1)` | Extrude closed 2D polygon |
+| `gear(teeth, module=1.0, h=1.0, pressure_angle=20, bore=0)` | Involute spur gear (tooth 0 on `+X`; mesh pair at center distance `m*(z1+z2)/2` with gear 2 rotated `180/z2` deg if `z2` is even, `0` deg if `z2` is odd) |
+| `extrude2d([(x,y), ...], z0, z1, holes=)` | Extrude closed 2D polygon with optional inner holes |
| `revolve([(r,z), ...], segs=32)` | Lathe profile around Z (auto-closes at `r=0`) |
| `loft([(z, [(x,y), ...]), ...], segs=24)` | Multi-section smooth loft (`segs` 8..128; warns if clamped) |
| `thread(r0, r1, pitch, turns)` | Watertight helical screw thread |
@@ -86,8 +96,9 @@ EOF
- **Transforms & Relational Placement:**
- `move(x, y, z)` | `rot(rx, ry, rz)` (degrees) | `scale(sx, sy, sz)`
- `on(base)` (rests cleanly on top of `base`) | `align(x|y|z, min|center|max, val)` | `align_z0(z)`
-- **Materials & Spatial Queries:**
+- **Materials, State & Spatial Queries:**
- `mat("name", color=(r,g,b), metallic=0.1, roughness=0.5)` | `color(r,g,b)`
+ - `del("name")` — remove a named part from the scene.
- `section(part, z)` — returns 2D cross-section loop count & area at plane `Z`.
- `clearance(a, b)` — returns exact minimum 3D distance between parts `a` and `b`.
@@ -95,6 +106,28 @@ EOF
## 4. Verified Recipes
+### Meshing Spur Gears (Single-Call Parametric Assembly)
+```forma
+units("mm")
+m = 2.0
+z1 = 12
+z2 = 24
+h = 8.0
+cd = m * (z1 + z2) / 2
+
+def ring(n, r, z=0) = [(r * cos(2 * pi * i / n), r * sin(2 * pi * i / n), z) for i in range(n)]
+
+_hole = cyl(2.5, h + 4)
+pinion = gear(z1, module=m, h=h, bore=3, z0=0)
+ | mat("steel", color=(0.62, 0.68, 0.76), metallic=0.9, roughness=0.25)
+wheel = gear(z2, module=m, h=h, bore=4, z0=0)
+ | cut(_hole, at=ring(6, 13, h / 2))
+ | rot(0, 0, 180 / z2)
+ | move(cd, 0, 0)
+ | mat("brass", color=(0.82, 0.66, 0.28), metallic=0.88, roughness=0.28)
+```
+Then render both gears together in one call: `export({ path: "gears.png", scene: true })` (and `export({ path: "gears.glb", scene: true })`). `_hole` stays local and does not appear in the exported scene.
+
### Brushed-Steel 5-Hole Mounting Flange
```forma
flange = box(4, 2, 0.4)
@@ -114,17 +147,17 @@ enclosure = box(3.0, 2.0, 1.0, z0=0)
### Helical Threaded Hex Bolt
```forma
-head = cyl(0.7, 0.4, segs=6, z0=0)
-shank = thread(0.32, 0.42, 0.16, 6) | align_z0(0.38)
-bolt = head | add(shank)
+_head = cyl(0.7, 0.4, segs=6, z0=0)
+_shank = thread(0.32, 0.42, 0.16, 6) | align_z0(0.38)
+bolt = _head | add(_shank)
| mat("titanium", color=(0.74, 0.78, 0.84), metallic=0.92, roughness=0.22)
```
### Ceramic Mug (Shell + Arc Handle)
```forma
-body = cyl(0.5, 1.0, segs=32, z0=0) | shell(0.08, open_top=true)
-handle = arc_tube(center=(0.48, 0, 0.5), rx=0.26, rz=0.28, start=-85, end=85, r=0.065)
-mug = body | add(handle)
+_body = cyl(0.5, 1.0, segs=32, z0=0) | shell(0.08, open_top=true)
+_handle = arc_tube(center=(0.48, 0, 0.5), rx=0.26, rz=0.28, start=-85, end=85, r=0.065)
+mug = _body | add(_handle)
| mat("terracotta", color=(0.72, 0.36, 0.24), metallic=0.0, roughness=0.72)
```
@@ -135,5 +168,6 @@ mug = body | add(handle)
- **Through-cuts:** Always make cutting cylinders/boxes taller than the target solid (e.g., cut a `0.4`-thick plate with a `1.0`-tall cylinder) to avoid grazing coplanar ambiguity.
- **Overlapping joins:** When joining two solids with `add()` (like a bolt head + thread or mug body + handle), overlap them slightly (`0.02` units) rather than kissing at an exact zero-thickness plane.
- **Bevel order:** Apply `bevel(vertical, w)` *before* `shell(t)` when hollowing an enclosure so inner and outer walls stay clean and uniform.
-- **Batch multi-hole cuts:** Pass a coordinate list `cut(cyl(r, h), at=[(x1,y1,0), ...])` instead of chaining separate `cut()` calls — it is faster and produces cleaner topology.
-- **Strict verification:** Never deliver a mesh that fails `--strict` (`WT=ok NM=0`). If a boolean fails, adjust cutter clearance/overlap or roll back with `tx(action="undo")`.
+- **Batch multi-hole cuts:** Pass a coordinate list (or comprehension `[... for i in range(n)]`) to `cut(cyl(r, h), at=...)` instead of chaining separate `cut()` calls — it is faster and produces cleaner topology.
+- **Keep scenes clean:** Prefix intermediate meshes with `_` (`_cut`, `_body`) so only final parts enter `scene.parts`, or remove stale parts with `del("name")`.
+- **Strict verification:** Never deliver a mesh that fails `--strict` (`WT=ok NM=0`). `eval(strict=true)` auto-rolls back failures cleanly; use `tx(action="undo")` if a valid edit needs reverting.
diff --git a/contribute/craftsmanship.md b/contribute/craftsmanship.md
index d8d60bc..10227ad 100644
--- a/contribute/craftsmanship.md
+++ b/contribute/craftsmanship.md
@@ -22,19 +22,23 @@ Instead, split quality feedback into:
1. **Deterministic Geometric Craftsmanship Critic (`forma lint` / `--critique`, `invariants.rs`):**
- Emits zero tokens on clean builds.
- Flags unintended floating shells, grazing contacts (`0 <= clearance < 1e-3`), thin walls via inward BVH rays, center-of-mass stability/tipping overhang, and an opt-in "un-beveled raw 90° box" lint.
+ - **Assembly Contact Graph (`spatial.rs`):** Computes an exact pairwise part-contact summary (`INTERSECTING`, `CONTACT`, `NEAR_GAP`, `DISJOINT`) using `spatial::clearance()` and emits an advisory note when separate parts meet flush along a mating face with no interlocking geometry or aligned bores. Semantic "missing hardware" judgment (e.g. whether a panel needs a hinge, rail, or handle) intentionally stays in **Layer B** (the host frontier LLM) rather than bundling a category-specific neural graph predictor such as GraFu (Zhao et al., SIGGRAPH Asia 2026).
-2. **Declarative Spatial Assertions (`assert` in `Forma-Pipe`):**
+2. **Declarative Spatial Assertions & Stateless Articulation Sweeps (`assert` in `Forma-Pipe`):**
- 1-line engineering contracts that auto-rollback with exact deltas on failure:
```text
assert clearance(shaft, bore) >= 0.005
assert connected(assembly)
assert grounded(base, z=0)
assert section_loops(flange, z=0) == 6
+ assert swing_clear(lid, housing, origin=(0,-0.05,0.04), axis=(1,0,0), deg=110) >= 0.0003
+ assert slide_clear(drawer, chassis, dir=(0,-1,0), dist=0.08) >= 0.0003
```
+ - **Stateless Articulation Clearance (`swing_clear` / `slide_clear`):** Inspired by the geometric swing-collision testing and motion rectification stage of *Functionalization / GraFu* ([Zhao et al., SIGGRAPH Asia 2026](https://mingrui-zhao.github.io/Functionalization/), `arXiv:2605.18010`), samples rigid-transform poses along a revolute arc or prismatic travel with AABB pruning + `spatial::clearance()`, reporting the exact collision angle/distance and hit centroid in `< 5 ms` without introducing persistent rigging or animation state into core `Scene`.
3. **Pure Parametric Macros (`def`) + Lazy Industrial-Design Stdlib (`inspect(topic="stdlib")`):**
- Reusable sub-assemblies (`def standoff(r_out, r_in, h) = ...`).
- - On-demand high-craft detail recipes (counterbored bosses, gusset ribs, snap-fit lips, flanged collars, Gothic arches) loaded lazily via `inspect(topic=...)` at **0 base-schema tokens**.
+ - On-demand high-craft detail recipes (counterbored bosses, gusset ribs, snap-fit lips, flanged collars, knuckle hinges, sliding rails, Gothic arches) loaded lazily via `inspect(topic=...)` at **0 base-schema tokens**.
4. **Visual-Critique Renderer Modes (`render.rs`):**
- `mode="section|wire|scale"` — mid-plane cutaways (exposing internal walls and clearances), clay+wireframe overlays, and orthographic ruler ticks for a tight 2-pass visual refinement loop.
diff --git a/contribute/forma-print.md b/contribute/forma-print.md
index dc9648d..6ebd303 100644
--- a/contribute/forma-print.md
+++ b/contribute/forma-print.md
@@ -34,7 +34,7 @@
| `formlabs_fuse_1p` | SLS | Laser Powder Bed | `165 × 165 × 300` | `~110 µm` laser | Zero supports; requires powder escape holes & ≥0.5 mm clearance |
> [!NOTE]
-> **Critical Unit Bridge (`meters` → `millimeters`):** Core Forma uses Z-up **meters** (`3MF` writes `unit="meter"`, `STEP` writes `SI_UNIT($,.METRE.)`), whereas slicers expect **millimeters**. `forma-print` should expose `--unit m|mm|auto` / `--scale`, emitting `unit="millimeter"` in `.3mf` and `SI_UNIT(.MILLI.,.METRE.)` in `.step`.
+> **Unit Support Already in Core (`v0.4.2`):** Core Forma supports `units("mm")` / `--unit mm` (defaulting to metres), emitting `unit="millimeter"` in `.3mf`, `SI_UNIT(.MILLI.,.METRE.)` in `.step`, millimetre labels in `.svg`, and metre-scaled `.glb`. `forma-print` should read `Scene.unit` directly and convert coordinates to millimetres for printer DFM checks (defaulting to mm or warning if a meter-scaled model exceeds the build plate).
### 1.2 Printability Physics & Pure-Rust Detection Math
@@ -45,6 +45,7 @@
| **Floating Islands (Z-Minima)** | Fatal without supports | **Catastrophic** (cured flake tears FEP/LCD) | N/A | Vertex-adjacency local Z-minima above `z_min` + `spatial::section_z` slice-to-slice XY overlap check (new loop with 0 overlap below = floating island). |
| **Bridge Spans** | Safe `≤ 10–25 mm` (PLA/PETG), `≤ 8–12 mm` (ABS) | Poor (`≤ 2–3 mm`) | Unlimited | Horizontal downward planar clusters (`n.z < -0.98`, `z > z_min + layer_h`): classify supported vs open boundary edges and span width. |
| **XY Clearances & Shrinkage** | Tight `0.15 mm`, snug `0.20 mm`, sliding/PIP `0.30–0.40 mm` | Tight `0.10 mm`, sliding `0.20–0.30 mm` | `≥ 0.50 mm` (powder clearing) | `forma_core::spatial::clearance(a, b)` on scene part pairs; flag fusing gaps `< min_clearance` or intersections. |
+| **Articulated / PIP Travel** | Rest `≥ 0.30–0.40 mm`; full travel `> 0`; pin axis aligned against layer shear | Rest `≥ 0.20–0.30 mm`; drain resin traps in knuckles | Rest `≥ 0.50 mm` for powder escape across joint | Stateless revolute/prismatic swept clearance (`swing_clear` / `slide_clear`) across full operating range + joint-axis orientation check against build Z. |
| **Bed Adhesion & Tipping** | Elephant's foot `0.15–0.30 mm`; warn if contact `< 100 mm²` or `H / width > 4` | Usually angled 30–45° on raft | N/A | Bed-face area sum + 2D convex hull of bed footprint + divergence-theorem Center of Mass `(com.x, com.y)` inside-hull check. |
| **SLA Suction Cups & Traps** | N/A | Vacuum tears layers / trapped liquid resin cracks part; needs ≥2 holes `Ø ≥ 3.5 mm` | Trapped powder; needs ≥2 holes `Ø ≥ 5.0 mm` | Track CW inner hole loops across `section_z` slices: closed-top downward-open cavity = **suction cup**; enclosed negative shell = **trapped cavity**. |
| **AMS / MMU Swap Waste** | `~0.4–1.5 g` purge + `~45–90 s` per swap on single-nozzle AMS/MMU | Single vat | Single bed | Count unique `mat_id` transitions per Z-layer band; estimate purge grams and recommend orientation minimizing color-change layers. |
@@ -125,7 +126,8 @@ flowchart LR
- **SLA Suction-Cup & Trapped-Cavity Detector:** Slice-graph tracking of CW inner loops across `section_z` + enclosed negative shells (`~20–60 ms`), plus **auto-hollow + lowest-Z drain & top vent holes** (`solidify_mesh` + boolean plugs).
- **Multi-Part & Multi-Plate 2D Nesting (`nest.rs`):** Reuses `uv.rs`'s convex-hull rotating calipers + MaxRects packer (`< 10 ms` for 50 parts), including purge-tower exclusion zones and automatic multi-plate spillover (`plate_1.json`, `plate_2.json`, ...).
- **Auto-Split Oversized Parts (`split.rs`):** Minimum-cross-section `bisect_mesh` + interlocking **15° dovetail** or **clearance-compensated alignment pin/socket** boolean joints.
-- **Print-Native Ops (`ops_print.rs`):** `teardrop()` horizontal holes, `counterbore_bridged()` sacrificial 1-layer ceilings, `heat_insert()` (M2–M5 CNC Kitchen/Voron specs), `thread_printable()` (45° flanks + clearance), `elephant_chamfer()`, `brim_ears()`, `snap_fit()`, and `modifier_part` tagging.
+- **Print-Native Ops & Functional PIP Mechanisms (`ops_print.rs`):** `teardrop()` horizontal holes, `counterbore_bridged()` sacrificial 1-layer ceilings, `heat_insert()` (M2–M5 CNC Kitchen/Voron specs), `thread_printable()` (45° flanks + clearance), `elephant_chamfer()`, `brim_ears()`, `snap_fit()`, `modifier_part` tagging, plus parametric print-in-place joints — `pip_hinge()` (45° chamfered conical pins, zero supports), `dovetail_rail()`, and `living_hinge()` — parameterized directly by active printer profile clearances.
+- **Coupled Mechanism DFM & Collision-First Mount Selection (`dfm.rs` / `orient.rs`):** Inspired by the mechanical grounding and swing-collision testing (`--hinge=auto`) of *Functionalization / GraFu* ([Zhao et al., SIGGRAPH Asia 2026](https://mingrui-zhao.github.io/Functionalization/), `arXiv:2605.18010`), verifies both **rest-pose anti-fusion clearance** (`>= profile.pip_clearance`) and **full-travel swept clearance** (`swing_clear` / `slide_clear`), flags weak layer-line shear on hinge pins / snap clips during `orient.rs`, and deterministically selects collision-free hinge/rail mount offsets without external template assets or ML weights.
- **`@forma-3d/print` WASM package.**
### Tier 3 — Slicer CLI Bridge & LAN Fleet Dispatch (opt-in features)
diff --git a/contribute/forma-ue.md b/contribute/forma-ue.md
index ea3aa6a..7c9e348 100644
--- a/contribute/forma-ue.md
+++ b/contribute/forma-ue.md
@@ -11,7 +11,7 @@
- **Spec-Compliant `.glb` (glTF 2.0 Y-Up) into UE5 Interchange:** Named `pbrMetallicRoughness` material slots (`baseColorFactor`, `metallicFactor`, `roughnessFactor`) and per-face material assignment.
- **Clean Shading Normals:** `smooth(angle=35, weighted=true)` computes area/angle-weighted auto-smooth normals with welded vertices.
-- **Game-Ready `TEXCOORD_0` UVs:** Pure-Rust LSCM conformal unwrapping + uniform texel density + non-overlapping `[0, 1]^2` atlas packing (`76.32%` Tier-1 / `75.66%` 12-mesh mean utilization, `1.0038` stretch, `0` inversions).
+- **Game-Ready `TEXCOORD_0` UVs:** Pure-Rust LSCM conformal unwrapping + uniform texel density + non-overlapping `[0, 1]^2` atlas packing (`~75.7%` 12-mesh mean utilization, `1.0038` stretch, `0` inversions across `bench/verify_tier1_parity.py`).
- **Multi-Object Named Scene Graphs:** `--scene` / `scene: true` preserves named parts as separate glTF nodes with shared `Arc<PolyMesh>` buffer instancing.
- **Watertight LOD Decimation:** Link-Condition QEM `decimate(ratio=...)`.
@@ -28,7 +28,7 @@
## 3. Zero-Bloat `forma-ue` Addon Architecture
- **Workspace isolation:** `crates/forma-ue` listed in `workspace.members`, excluded from `default-members` (`0 bytes` & `0 tokens` impact on core `forma` / `forma-mcp` / `forma.wasm`).
-- **Invocation:** Standalone `forma-ue` CLI, Git-style `forma ue ...` plugin dispatch, opt-in `forma-ue --mcp` (~250–350 tokens), optional `--features ue` flag (~50 KB delta, 0 new crates).
+- **Invocation:** Standalone `forma-ue` CLI, planned Git-style `forma ue ...` plugin dispatch (requires adding subcommand delegation in `crates/forma-cli`), opt-in `forma-ue --mcp` (~250–350 tokens), optional `--features ue` flag (~50 KB delta, 0 new crates).
- **Core Capabilities:**
1. **UE-Native Scale & Scene Welding:** Centimeter scale (`1 m → 100 cm`) + vertex welding on multi-node scene exports for clean UE5 Interchange import.
2. **Auto Collision Hulls (`UCX_` / `UBX_`):** Pure-Rust 3D QuickHull per connected component/part emitted as sibling nodes matching UE's collision naming (`UCX_<Part>_00`, `UBX_<Part>_00`).
diff --git a/docs/AUTORESEARCH_HILLCLIMB.md b/docs/AUTORESEARCH_HILLCLIMB.md
index 610b479..0f2437c 100644
--- a/docs/AUTORESEARCH_HILLCLIMB.md
+++ b/docs/AUTORESEARCH_HILLCLIMB.md
@@ -1,3 +1,6 @@
+> [!NOTE]
+> **Archived optimization log (`v0.2`–`v0.4`).** Some historical sizes, token counts, and early WASM symbol names (such as `eval_pipe_text`) have since evolved (current WASM C-ABI uses `forma_session_*`). For current `v0.4.2` APIs and specs, see [docs/reference/apis.md](reference/apis.md).
+
# `forma` v0.2 Autoresearch Hill-Climb & Universal Core Upgrade Log
## 1. Kernel Autoresearch Hill-Climb Progression (100% Pure Rust, Zero New Dependencies)
diff --git a/docs/EXTENDED_BENCHMARK_REPORT.md b/docs/EXTENDED_BENCHMARK_REPORT.md
index dcf0e71..1e341a1 100644
--- a/docs/EXTENDED_BENCHMARK_REPORT.md
+++ b/docs/EXTENDED_BENCHMARK_REPORT.md
@@ -1,13 +1,13 @@
-# Extended Benchmark Report: 12 Recent (Late-2026) Models Across 10 Labs & Reasoning-Effort Scaling
+# Extended Benchmark Report: 12 Recent (Late-2026) Models Across 9 Labs & Reasoning-Effort Scaling
## 1. Scope & Methodology
-All models tested are recent **Sept–Dec 2026** releases spanning **10 distinct labs** (Anthropic, Google, OpenAI, Tencent, Alibaba/Qwen, Z.ai, DeepSeek, xAI, Mistral) and multiple size tiers (flagship, mid-tier, flash/mini). Every model is evaluated head-to-head on stock headless **Blender 5.3.0 (`bpy`)** vs. **`Forma-Pipe`** on the 6-task cross-category benchmark (`flange_plate`, `pipe_tee`, `beveled_enclosure`, `hex_nut`, `subdiv_mug`, `pedestal_bowl`), up to 3 turns each, verified independently with `trimesh` + `scipy` (Chamfer, Hausdorff-99, Generalized Winding Number Volumetric IoU, watertight/0-non-manifold checks).
+All models tested are recent **Sept–Dec 2026** releases spanning **9 distinct labs** (Anthropic, Google, OpenAI, Tencent, Alibaba/Qwen, Z.ai, DeepSeek, xAI, Mistral) and multiple size tiers (flagship, mid-tier, flash/mini). Every model is evaluated head-to-head on stock headless **Blender 5.3.0 (`bpy`)** vs. **`Forma-Pipe`** on the 6-task cross-category benchmark (`flange_plate`, `pipe_tee`, `beveled_enclosure`, `hex_nut`, `subdiv_mug`, `pedestal_bowl`), up to 3 turns each, verified independently with `trimesh` + `scipy` (Chamfer, Hausdorff-99, Generalized Winding Number Volumetric IoU, watertight/0-non-manifold checks).
Total empirical trials logged in [`bench/results/matrix_trials.jsonl`](../bench/results/matrix_trials.jsonl) + Phase 1–2 suites: **254 paired matrix trials** (plus 144 earlier 12-task ablation trials).
---
-## 2. Part A — Cross-Lab Generalization (12 Late-2026 Models, 10 Labs)
+## 2. Part A — Cross-Lab Generalization (12 Late-2026 Models, 9 Labs)
| Model (Release Date) | Level | `bpy` P1/P3 | `bpy` API / Comp | `bpy` IoU | `Forma` P1/P3 | `Forma` API / Comp | `Forma` IoU | API Gain | Comp Gain |
|---|---|---:|---:|---:|---:|---:|---:|---:|---:|
diff --git a/docs/PHASE1_ARCHITECTURE_AUDIT.md b/docs/PHASE1_ARCHITECTURE_AUDIT.md
index d74f5fc..0ebc978 100644
--- a/docs/PHASE1_ARCHITECTURE_AUDIT.md
+++ b/docs/PHASE1_ARCHITECTURE_AUDIT.md
@@ -1,3 +1,6 @@
+> [!NOTE]
+> **Archived engineering snapshot (initial v0.1 architecture study).** Binary sizes, memory figures, and architecture details reflect the initial pre-build Blender audit. For current `v0.4.2` architecture and specs, see [docs/explanation/architecture.md](explanation/architecture.md) and [README.md](../README.md).
+
# Phase 1.1 — Blender 5.3.0 Architecture Audit & Build-vs-Slice Decision Record
## 1. Raw Measurements on Installed Blender 5.3.0 (macOS arm64)
diff --git a/docs/PHASE1_BASELINE_REPORT.md b/docs/PHASE1_BASELINE_REPORT.md
index 26c5518..04ee822 100644
--- a/docs/PHASE1_BASELINE_REPORT.md
+++ b/docs/PHASE1_BASELINE_REPORT.md
@@ -1,3 +1,6 @@
+> [!NOTE]
+> **Archived benchmark snapshot (v0.1 baseline study).** For current documentation and APIs, see [docs/README.md](README.md).
+
# Phase 1.2 — Baseline Evaluation Report: Stock Headless Blender 5.3 (`bpy`)
## 1. Experimental Setup
diff --git a/docs/PHASE2_LANGUAGE_ABLATION.md b/docs/PHASE2_LANGUAGE_ABLATION.md
index a138d22..c493242 100644
--- a/docs/PHASE2_LANGUAGE_ABLATION.md
+++ b/docs/PHASE2_LANGUAGE_ABLATION.md
@@ -1,3 +1,6 @@
+> [!NOTE]
+> **Archived benchmark snapshot (v0.1 dialect ablation study).** Token counts and specs reflect the v0.1 ablation experiment; for current `Forma-Pipe` and MCP specs, see [docs/reference/language-and-formats.md](reference/language-and-formats.md) and [docs/reference/apis.md](reference/apis.md).
+
# Phase 2.4 — Empirical Command Language Ablation & Pareto Frontier Report
## 1. Hypothesis Tested
diff --git a/docs/VERIFICATION_REPORT.md b/docs/VERIFICATION_REPORT.md
index c21ea7c..c5e1697 100644
--- a/docs/VERIFICATION_REPORT.md
+++ b/docs/VERIFICATION_REPORT.md
@@ -1,3 +1,6 @@
+> [!NOTE]
+> **Archived verification snapshot (v0.2 release gate).** Measurements such as binary size (`1.1 MB`), peak RSS (`2.16 MB`), and MCP tokens (`722`) reflect v0.2 before later features (`.step`, `.3mf`, `units()`, LSCM UVs, Surface Nets remeshing). For current `v0.4.2` footprints and specs, see [README.md](../README.md) and [docs/reference/apis.md](reference/apis.md).
+
# Phase 3.6 — Independent Automated Verification Report
All gates below are executed independently of `forma-core`'s internal assertions via [`bench/gate_verify.py`](../bench/gate_verify.py), [`bench/verify.py`](../bench/verify.py), and [`crates/forma-core/tests/fuzz_invariants.rs`](../crates/forma-core/tests/fuzz_invariants.rs).
diff --git a/docs/explanation/architecture.md b/docs/explanation/architecture.md
index 28eb2d6..d942ea0 100644
--- a/docs/explanation/architecture.md
+++ b/docs/explanation/architecture.md
@@ -11,7 +11,7 @@ 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)"]
+ IMG["FROM scratch (< 5 MB musl)"]
SRV --> IMG
end
subgraph Core["default-members (Core)"]
@@ -30,9 +30,9 @@ flowchart LR
### 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.
+- **`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 on-demand topic specifications.
+- **`forma-cli`**: The native command-line binary (`forma`). It wires terminal flags and exit codes onto `forma-lang` and `forma-core` (including the `.blend` Blender bridge in `forma-core::export`).
+- **`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 (`723` tokens).
### Opt-in surfaces (excluded from `default-members`)
@@ -70,15 +70,15 @@ 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)"]
+ INSP -. "0-tok preload" .-> TOPICS["Topic Specs (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"]
+ STATE --> EXP["export(path, scene?) -> GLB / STEP / 3MF / BLEND / 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)`.
+- The base tool catalog (`eval`, `inspect`, `tx`, `export`) carries only the compact `Forma-Pipe` core grammar inside `eval`'s description (`723` `o200k` tokens total).
+- Specialized domain capabilities (deformers and solidify, Bezier/NURBS curves, LSCM UV unwrapping and QEM decimation, Surface Nets remeshing and bisect, and multi-object glTF/Blender 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
diff --git a/docs/explanation/why-forma.md b/docs/explanation/why-forma.md
index d99688c..e622496 100644
--- a/docs/explanation/why-forma.md
+++ b/docs/explanation/why-forma.md
@@ -36,7 +36,7 @@ Instead of returning silent success or forcing an agent to render and decode ima
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.
+- **Sub-800-token MCP surface (`723` `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.
diff --git a/docs/forma_launch_cues.json b/docs/forma_launch_cues.json
deleted file mode 100644
index 9fff202..0000000
--- a/docs/forma_launch_cues.json
+++ /dev/null
@@ -1,51 +0,0 @@
-{
- "episode": "Forma Launch — The 1.1 MB 3D Engine Built for AI Agents",
- "style": "Direction D — PRISMATLAS 2.0 Manifesto",
- "voice_model": "elevenlabs/eleven-v4",
- "voice_id": "george",
- "tail_pad_sec": 2.5,
- "cues": [
- {
- "id": "forma_c01",
- "act": "Act I — The Hook",
- "scene": "Why AI Struggles With 3D CAD",
- "pre_gap_sec": 2.0,
- "narration": "Ask an AI model to build a simple 3D part in Blender, and watch what happens. It writes sixty lines of fragile Python... guesses integer vertex indices... launches a nine-hundred-megabyte desktop app... burns two thousand tokens... and half the time hands you a broken mesh with holes in it. Why? Because Blender was designed for human hands and eyeballs—not for language models."
- },
- {
- "id": "forma_c02",
- "act": "Act II — Introducing Forma",
- "scene": "One Pipeline. One Megabyte. Watertight By Construction.",
- "pre_gap_sec": 1.6,
- "narration": "Meet Forma. A clean-room, pure-Rust 3D B-rep modeling engine built from first principles for AI agents. The entire static binary—engine, CLI, MCP server, and built-in studio renderer—is one-point-one megabytes. No GPU. No GUI. No giant runtime. Instead of sixty lines of imperative boilerplate, an agent writes four lines of declarative pipe code: start with a box, bevel the vertical edges, shell it hollow, and cut five holes in a single pass."
- },
- {
- "id": "forma_c03",
- "act": "Act III — Semantic Superpowers",
- "scene": "Zero Vertex Indices. Instant Feedback.",
- "pre_gap_sec": 1.6,
- "narration": "Forma replaces brittle index math with semantic selectors like top rim, vertical, and sides. Every operation is transactional—if anything goes non-manifold, it rolls back automatically. And after every step, Forma replies with a tiny hundred-token spatial diff: exact bounding box, volume, watertight check, clearance, cross-section loops, and even a four-view shaded preview rendered in four milliseconds."
- },
- {
- "id": "forma_c04",
- "act": "Act IV — The Benchmark Gains",
- "scene": "12 Models. 10 Labs. Every Single One Wins.",
- "pre_gap_sec": 1.8,
- "narration": "We benchmarked Forma head-to-head against stock headless Blender across twelve late-twenty-twenty-six models from ten labs—including Claude, Gemini, GPT, Qwen, DeepSeek, Grok, and GLM—verified independently with volumetric IoU and real slicer checks. Every single model won. Across the board, Forma cut completion tokens by three-point-five to fifteen times, slashed API cost by up to nine times, and pushed accuracy to ninety-five to one hundred percent—even doubling small models like Claude Haiku from fifty percent to one hundred percent one-shot."
- },
- {
- "id": "forma_c05",
- "act": "Act V — Ultimate Speed",
- "scene": "From 1.3 Seconds Down to 14 Milliseconds",
- "pre_gap_sec": 1.6,
- "narration": "And it is absurdly fast. With a BVH-localized Möller-guarded boolean kernel, batch CSG, and zero-HashMap geometry passes, Forma executes and exports a full watertight GLB in fourteen milliseconds—nearly ninety times faster than headless Blender, using one hundred times less RAM. Every mesh exports cleanly to GLB with PBR materials and UVs, STL, OBJ, or straight into Blender."
- },
- {
- "id": "forma_c06",
- "act": "Act VI — Outro & Call to Action",
- "scene": "Drop-In CLI, MCP Server & GBNF Grammar",
- "pre_gap_sec": 1.4,
- "narration": "Plug Forma into any agent in seconds—over Unix pipes, via our seven-hundred-seventy-six-token MCP server, or locked to zero syntax errors with our formal GBNF grammar. One megabyte. Fourteen milliseconds. Watertight 3D, built for AI. Try Forma today."
- }
- ]
-}
diff --git a/docs/forma_launch_script.md b/docs/forma_launch_script.md
deleted file mode 100644
index a55df70..0000000
--- a/docs/forma_launch_script.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# FORMA LAUNCH VIDEO — Simple Production Script
-**Title:** *Forma: The 1.1 MB 3D Engine Built for AI Agents (89× Faster Than Blender)*
-**Runtime:** `~2:15` (`~365` words · 6 beats @ ~145 WPM · directly matches `forma_launch_cues.json` for `conductor/tutorials`)
-**Voice:** ElevenLabs v4 (`george`) — crisp, confident, fast-paced product launch cadence
-
----
-
-## Beat 01 — The Hook (`0:00 – 0:22`) · `forma_c01`
-**Visual:** Split dark canvas. Left: fast-scrolling 60-line Blender `bpy` Python script (`bmesh`, `ops`, `modifiers`, fragile index loops) + `953 MB` / `1,307 ms` / `2,000+ tokens` red counters ticking up. Right: broken mesh flashing red non-manifold edges (`NM=22`, `WT=FALSE`).
-
-> **VO:** "Ask an AI model to build a simple 3D part in Blender, and watch what happens. It writes sixty lines of fragile Python... guesses integer vertex indices... launches a nine-hundred-megabyte desktop app... burns two thousand tokens... and half the time hands you a broken mesh with holes in it. Why? Because Blender was designed for human hands and eyeballs—not for language models."
-
----
-
-## Beat 02 — Introducing Forma (`0:22 – 0:48`) · `forma_c02`
-**Visual:** Clean wipe into bright drafting grid. **`FORMA`** wordmark snaps in with 3 crisp pills: `1.1 MB BINARY` · `PURE RUST` · `ZERO GPU`. Below: live 4-line `Forma-Pipe` snippet types in on the left while the 3D steel 5-hole flange snaps cleanly into view on the right (`WT=OK`):
-```forma
-flange = box(4, 2, 0.4)
- | mat("steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
- | cut(cyl(0.5, 1))
- | cut(cyl(0.25, 1), at=[(-1.4,-0.5,0), (-1.4,0.5,0), (1.4,-0.5,0), (1.4,0.5,0)])
-```
-
-> **VO:** "Meet Forma. A clean-room, pure-Rust 3D B-rep modeling engine built from first principles for AI agents. The entire static binary—engine, CLI, MCP server, and built-in studio renderer—is one-point-one megabytes. No GPU. No GUI. No giant runtime. Instead of sixty lines of imperative boilerplate, an agent writes four lines of declarative pipe code: start with a box, bevel the vertical edges, shell it hollow, and cut five holes in a single pass."
-
----
-
-## Beat 03 — Semantic Superpowers (`0:48 – 1:12`) · `forma_c03`
-**Visual:** Quick montage of highlighted semantic edges (`top_rim`, `vertical`, `sides`) glowing on a hex nut & enclosure, followed by the compact ~100-token terminal diff card (`OK [6.9ms] WT=ok NM=0 vol=2.576 | section loops=6 area=6.44`) and the crisp **4-view shaded PNG** (`F / R / T / ISO`) popping in with a `3.9 ms` badge.
-
-> **VO:** "Forma replaces brittle index math with semantic selectors like top rim, vertical, and sides. Every operation is transactional—if anything goes non-manifold, it rolls back automatically. And after every step, Forma replies with a tiny hundred-token spatial diff: exact bounding box, volume, watertight check, clearance, cross-section loops, and even a four-view shaded preview rendered in four milliseconds."
-
----
-
-## Beat 04 — The Benchmark Gains (`1:12 – 1:40`) · `forma_c04`
-**Visual:** Animated Tufte-style horizontal bar chart & Pareto scatter plot comparing **Stock Blender 5.3 (`bpy`)** vs **`Forma`** across **12 models / 10 labs**:
-- **Completion Tokens:** `3.5× – 15.5×` fewer tokens
-- **API Cost (USD):** up to `9.7×` cheaper (`$0.13` vs `$1.29` at high reasoning)
-- **Pass Rate:** `95.5% – 100%` Pass@2/3 (vs `79% – 83%` on `bpy`)
-- **Spotlight Callout:** `Claude Haiku 5.5` Pass@1 jumps `50% → 100% (6/6)` on v0.2!
-
-> **VO:** "We benchmarked Forma head-to-head against stock headless Blender across twelve late-twenty-twenty-six models from ten labs—including Claude, Gemini, GPT, Qwen, DeepSeek, Grok, and GLM—verified independently with volumetric IoU and real slicer checks. Every single model won. Across the board, Forma cut completion tokens by three-point-five to fifteen times, slashed API cost by up to nine times, and pushed accuracy to ninety-five to one hundred percent—even doubling small models like Claude Haiku from fifty percent to one hundred percent one-shot."
-
----
-
-## Beat 05 — Ultimate Speed (`1:40 – 2:00`) · `forma_c05`
-**Visual:** Log-scale bar wipe showing kernel & end-to-end latency collapsing:
-- Blender 5.3 headless: **`1,307 ms` · `223 MB RAM` · `953 MB install`**
-- Forma v0.2: **`14.7 ms` (`89× faster`) · `2.16 MB RAM` (`103× less`) · `1.1 MB` (`866× smaller`)**
-- Export format pills lock in: `.GLB (PBR + UVs)` · `.STL` · `.OBJ` · `.BLEND` · `.PNG`.
-
-> **VO:** "And it is absurdly fast. With a BVH-localized Möller-guarded boolean kernel, batch CSG, and zero-HashMap geometry passes, Forma executes and exports a full watertight GLB in fourteen milliseconds—nearly ninety times faster than headless Blender, using one hundred times less RAM. Every mesh exports cleanly to GLB with PBR materials and UVs, STL, OBJ, or straight into Blender."
-
----
-
-## Beat 06 — Outro & Call to Action (`2:00 – 2:15`) · `forma_c06`
-**Visual:** Clean dark-to-dawn finale card showing 3 integration pills:
-- `CLI` (`forma eval --strict --out part.glb`)
-- `MCP` (`forma-mcp · 776 tokens`)
-- `GBNF` (`forma spec --gbnf · 0% syntax errors`)
-Closing tagline: **`FORMA — 1.1 MB · 14 ms · Watertight 3D for AI.`**
-
-> **VO:** "Plug Forma into any agent in seconds—over Unix pipes, via our seven-hundred-seventy-six-token MCP server, or locked to zero syntax errors with our formal GBNF grammar. One megabyte. Fourteen milliseconds. Watertight 3D, built for AI. Try Forma today."
diff --git a/docs/how-to/connect-ai-agents.md b/docs/how-to/connect-ai-agents.md
index df29d8b..d2e7361 100644
--- a/docs/how-to/connect-ai-agents.md
+++ b/docs/how-to/connect-ai-agents.md
@@ -4,7 +4,7 @@ Use this guide to connect an AI coding agent, cloud VM, or local LLM to Forma ov
## 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.
+Forma exposes a stdio JSON-RPC 2.0 MCP server (`protocolVersion: "2024-11-05"`) with four tools (`eval`, `inspect`, `tx`, `export`) totaling `721` `o200k` tokens.
### Zero-install setup with npm (`forma-3d-mcp`)
@@ -23,7 +23,7 @@ Add the following entry to your MCP client configuration (`.mcp.json` for Claude
### 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:
+If you built the native workspace (`cargo build --release`), point the client at `target/release/forma-mcp` for lower startup latency (both `forma-mcp` and `forma-3d-mcp` support `.blend` export whenever Blender is installed locally):
```json
{
@@ -48,18 +48,17 @@ printf '%s\n%s\n' \
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
+## Token-efficient agent sessions (batching, checkpoints, and progressive topic specs)
-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=...)`.
+1. **Batch complete parts or assemblies into 1–2 `eval` calls** with `{"code": "...", "strict": true}`. Scalar variables persist across MCP `eval` calls (and roll back with `tx`), `def name(p1, p2=default) = expr` and `[expr for i in range(n)]` avoid repetitive code, `_`-prefixed mesh variables (`_tmp = ...`) stay local without polluting `scene.parts`, and `del("name")` removes obsolete parts. If any statement fails or violates watertightness (`WT!=ok`, `NM>0`, `NaN`, or degenerate volume), Forma automatically rolls back both geometry and scalars.
+2. **Use checkpoints selectively.** Because `eval` already auto-rolls back on error, only call `tx` with `{"action": "checkpoint", "tag": "base"}` before genuinely exploratory edits you may want to discard even if they succeed. Revert with `{"action": "rollback", "tag": "base"}` or step back one evaluation with `{"action": "undo"}`.
+3. **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"|"lattice")`.
+ - `{"topic": "curves"}`: `bezier`, `nurbs`, `extrude2d(..., holes=...)`, `sweep`.
- `{"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}`).
+ - `{"topic": "scene"}`: multi-part scene export & rendering (`export(..., scene: true)` for `.glb`, `.blend`, `.png`, and `.svg`), `_tmp` locals, and `del("name")`.
+4. **Preview once and export:** Call `export` with `{"path": "preview.png", "scene": true, "size": 512}` (or `{"path": "blueprint.svg", "scene": true}`) to visually verify all named scene parts together with their materials — no dummy boolean-merged assembly needed — then export the final asset (`{"path": "model.glb"}`, `{"path": "model.blend"}`, or `{"path": "scene.glb", "scene": true}`).
## Option B: Drive Forma from a shell-capable agent or VM (`boat.dev`, E2B, Modal)
diff --git a/docs/how-to/deploy-http-server.md b/docs/how-to/deploy-http-server.md
index b5abbb5..d9749ae 100644
--- a/docs/how-to/deploy-http-server.md
+++ b/docs/how-to/deploy-http-server.md
@@ -33,7 +33,7 @@ Expected response:
## 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:
+The repository [`Dockerfile`](../../Dockerfile) builds static `musl` binaries (`forma-server` and `forma` using `--profile static-release`) and copies them into `FROM scratch` (`< 5 MB` final image) with `FORMA_BIND=0.0.0.0:8080` and port `8080` exposed:
```bash
docker build -t forma-server:0.4.2 .
@@ -80,14 +80,14 @@ Inspect the response headers for geometry telemetry:
- `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.
+Set `"format": "json"` (the default) when you want `ok`, `elapsed_ms`, `text`, `parts`, `diff`, and `warnings`, or `"format": "text"` for plain-text observations.
## 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)
+MESH_B64=$(base64 < input.glb | tr -d '\n')
curl -sS http://127.0.0.1:8080/v1/eval \
-H 'Content-Type: application/json' \
-d "{
diff --git a/docs/how-to/units-and-mesh-processing.md b/docs/how-to/units-and-mesh-processing.md
index 127f633..ef33a60 100644
--- a/docs/how-to/units-and-mesh-processing.md
+++ b/docs/how-to/units-and-mesh-processing.md
@@ -13,19 +13,19 @@ enclosure = box(100, 60, 25, z0=0)
| 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:
+You can also set the starting unit from outside the script via `--unit` on both CLIs (`forma` and `forma-3d`), `{ unit: "mm" }` in the JS/TS API, or `"unit": "mm"` in `forma-server` (`POST /v1/eval`):
```bash
forma eval --unit mm --out enclosure.3mf enclosure.forma
+npx forma-3d 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).
+- `.svg`: labels orthographic dimension callouts, size, and volume with your declared unit symbol (`mm`, `in`, `m`, etc.).
- `.stl` and `.obj`: have no standard unit metadata field and are written in raw model units.
## Import, normalize, and decimate an existing mesh
@@ -55,7 +55,7 @@ forma eval --strict --out clean.glb --render preview.png cleanup.forma
## 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).
+If you run `forma-server`, use `POST /v1/process` to perform Y-up to Z-up conversion (`"yup": true`), uniform or per-axis scaling (`"scale": 0.001` or `"scale": [sx, sy, sz]`), resting on `z = 0` (`"center_z0": true`), and QEM decimation (`"decimate"` and/or `"target_faces"`) in a single request. See [How to deploy Forma](deploy-http-server.md).
## Related references
diff --git a/docs/reference/apis.md b/docs/reference/apis.md
index d3f7544..fc231ee 100644
--- a/docs/reference/apis.md
+++ b/docs/reference/apis.md
@@ -9,16 +9,16 @@ Exact interface contracts verified against `wrong-nebula/forma` `v0.4.2` (`crate
- **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`).
+- **Token footprint**: `721` `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. |
+| `eval` | `{ code: string, strict?: boolean }` | `strict` defaults to `true`. Executes `Forma-Pipe` transactionally with auto-rollback on error or strict invariant failure. Scalar variables persist across calls (and roll back with `tx`); `_`-prefixed mesh vars stay local. 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 domain specification for that topic. |
+| `tx` | `{ action: "checkpoint" \| "rollback" \| "undo" \| "reset", tag?: string }` | `tag` defaults to `"default"`. Mutates or restores O(1) `Arc<PolyMesh>` scene snapshots (including scalar variables and `Scene.unit`). |
+| `export` | `{ path: string, part?: string, scene?: boolean, size?: integer }` | Writes `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.blend` (via local Blender bridge), or `.png` (`size` defaults to `512`). When `scene: true`, exports or renders all named parts together (`.glb`, `.blend`, `.png`, or `.svg`). |
## JavaScript / TypeScript / Edge WASM API (`forma-3d`)
@@ -40,8 +40,8 @@ Zero runtime dependencies and zero top-level `node:*` imports.
| `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>` |
+| `renderPng` | `renderPng(code: string, size?: number, opts?: ExportOptions)` | `Promise<Uint8Array>` |
+| `drawSvg` | `drawSvg(code: string, opts?: ExportOptions)` | `Promise<string>` |
| `getSpec` | `getSpec(opts?: SpecOptions)` | `Promise<string>` |
| `getSpecTopic` | `getSpecTopic(topic: string, opts?: TopicOptions)` | `Promise<string>` |
@@ -49,19 +49,21 @@ Zero runtime dependencies and zero top-level `node:*` imports.
- `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"`).
+- `SessionEvalOptions`: `{ dialect?: FormaDialect; strict?: boolean; unit?: FormaUnit | string }` (`strict` defaults to `true`, `dialect` defaults to `"pipe"`).
+- `EvalOptions extends SessionEvalOptions`: adds `{ wasm?: WasmSource }`.
- `ExportOptions extends EvalOptions`: adds `{ part?: string; size?: number }`.
-- `SpecOptions`: `{ dialect?: "pipe" | "compact"; gbnf?: boolean; wasm?: WasmSource }`.
+- `EngineSpecOptions`: `{ dialect?: FormaDialect; gbnf?: boolean }`; `SpecOptions extends EngineSpecOptions` adds `{ 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 }`.
+- `FormaObservation`: `{ ok: boolean; elapsed_ms: number; parts: Record<string, FormaInvariants>; diff: string; warnings: string[]; text: string }`.
+- `FormaInvariants`: `{ verts, edges, faces, tris, watertight, non_manifold_edges, boundary_edges, euler, genus, consistent_winding, degenerate_faces, nan_verts, components, signed_volume, volume, surface_area, bbox_min, bbox_max, size, tags }`.
### `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.spec(opts?: EngineSpecOptions): string`: returns the compiled language specification or GBNF grammar.
+- `engine.specTopic(topic: string): string`: returns the domain 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.setUnit(unit: FormaUnit | string): string`: sets the session model unit (`m|cm|mm|um|in|ft`).
+- `session.eval(code: string, opts?: SessionEvalOptions): 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.
@@ -86,9 +88,9 @@ Binary built with `cargo build --profile static-release -p forma-server` (exclud
| 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. |
+| `GET /spec` | Optional query `gbnf=1`, `dialect=compact`, or `topic=<name>` | `200 OK` `text/plain; charset=utf-8` |
+| `POST /v1/eval` | JSON `{ code, strict?, dialect?, format?, size?, part?, unit?, assets? }` | `format="json"` (default) returns JSON (`ok`, `elapsed_ms`, `text`, `parts`, `diff`, `warnings`); `format="text"` returns `text/plain`; `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? }` | `scale` accepts a uniform number or `[sx, sy, sz]`; `target_faces` works with or without `decimate`. Returns binary mesh/render (`output_format` defaults to `"glb"`) + `X-Forma-*` headers. |
### Binary response headers
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 351e233..0729061 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -22,12 +22,12 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo
| 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. |
+| `--unit`, `-u <m\|cm\|mm\|um\|in\|ft>` | `m` | Yes | Yes | 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). |
+| `--scene` | Disabled | Yes | Yes | Export all named parts as separate glTF 2.0 / Blender nodes when `--out` targets `.glb` or `.blend`. |
+| `--out`, `-o <path>` | None | Yes | Yes | Export mesh (`.glb`, `.obj`, `.stl`, `.3mf`, `.step`, `.blend` via Blender bridge). |
| `--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`). |
@@ -39,17 +39,16 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo
### `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|-]`
+- WASM: `forma-3d render [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--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|-]`
+- WASM: `forma-3d draw [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] --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`).
+- Both CLIs: `spec [--dialect pipe|compact] [--topic <deform|curves|uv|normals|remesh|scene>] [--gbnf]` (also accepts topic as a positional argument, e.g. `forma spec deform`).
## Exit codes
@@ -64,7 +63,7 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo
| 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`. |
+| `BLENDER_BIN` | Native `forma`/`forma-mcp` and Node `forma-3d`/`forma-3d-mcp` | `blender` on `PATH` (or macOS `/Applications/Blender.app/Contents/MacOS/Blender`) | Path to local Blender binary invoked when exporting `.blend`. |
| `FORMA_BIN` | `sandbox/forma.py` | Auto-discovered | Explicit path to static `forma` binary in air-gapped Python sandboxes. |
## Native vs WASM parity matrix
@@ -73,8 +72,8 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo
| --- | --- | --- | --- |
| `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 `--unit` / `-u` flag | Yes | Yes | Sets initial unit before evaluating the script. |
| 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. |
+| `.blend` stock-Blender bridge export | Yes | Yes (Node CLI/MCP) | Uses local Blender (`BLENDER_BIN` or `blender` on `PATH`). |
+| Built-in `mcp` subcommand | Separate binary (`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.md
index e88dadd..614337e 100644
--- a/docs/reference/language-and-formats.md
+++ b/docs/reference/language-and-formats.md
@@ -5,16 +5,17 @@ Authoritative specification for Forma's two modeling dialects, semantic selector
## 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.
+- **Default unit**: `1.0` equals one meter (`Unit::Meter`) unless overridden by `units("...")`, `--unit`, JS `{ unit }`, or HTTP `unit`.
+- **Export target**: The last assigned or modified part exports by default unless a specific `part` or multi-part `scene` export/render (`scene: true` / `--scene` for `.glb`, `.blend`, `.png`, or `.svg`) is requested.
+- **Variables & scope**: Scalar variables persist across stateful `eval` calls (such as MCP sessions) and roll back with `tx`. Mesh variables prefixed with `_` (for example `_tmp = ...`) stay local to the script and do not pollute `scene.parts` or `scene: true` exports. Use `del("name")` to delete a named part from `scene.parts`.
+- **Transactional rollback**: Every `eval_script` call pushes an undo snapshot before execution and restores geometry, scalar variables, 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`) |
+| `Forma-Pipe` (default) | `pipe`, `forma-pipe`, `a`, `default` | Expression pipeline: `name = prim \| op \| op` with multi-line `\|`, macros (`def name(p1, p2=default) = expr`), list comprehensions (`[expr for i in range(n)]`, 1/2/3-arg `range`), arithmetic (`+ - * / sqrt sin cos tan asin acos atan atan2 abs deg rad 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`, `del`, `ckpt`, `rb`, `undo`, `units`). | Built-in EBNF (`spec --dialect compact`) |
## Core `Forma-Pipe` primitives
@@ -30,38 +31,41 @@ Authoritative specification for Forma's two modeling dialects, semantic selector
| `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`). |
+| `gear` | `gear(teeth, module=1.0, h=1.0, pressure_angle=20, bore=0)` | Involute spur gear (tooth 0 on `+X`; meshing pair at center distance `m*(z1+z2)/2` with gear 2 rotated `180/z2` degrees when `z2` is even, `0` degrees when `z2` is odd). |
| `loft` | `loft([(z, [(x, y), ...]), ...])` | Lofted solid between planar cross-sections at heights `z`. |
-| `thread` | `thread(r0, r1, pitch, turns)` | Helical screw thread solid. |
+| `thread` | `thread(r0, r1, pitch, turns)` | Helical screw thread solid (`r0`/`r_minor`, `r1`/`r_major`). |
+| `sweep` | `sweep(profile2d, path3d, scale_end=1.0, twist=0.0, closed=false)` | Parallel-transport 3D rail sweep with optional taper and twist. |
+| `text3d` | `text3d("TEXT", height=0.5, depth=0.1)` | Watertight 3D extruded vector text (`size=` alias supported). |
## 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)` |
+| Patterns and symmetry | `mirror(x\|y\|z)`, `array(n, step)` / `pattern_linear(n, step)`, `radial(n, r=, axis=z)` / `pattern_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")` |
+| 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, gap=0)`, `align_z0(z)` |
+| Materials | `mat(name, color=(r, g, b), metallic=0.1, roughness=0.5, faces=)`, `color(r, g, b)` |
+| Queries, state, and units | `clearance(a, b)`, `section(part, z)`, `units("m\|cm\|mm\|um\|in\|ft")`, `checkpoint(tag)`, `rollback(tag)`, `undo()`, `del(name)` |
## 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` |
+| Edge selectors (`bevel`) | `vertical`, `horizontal`, `top_rim`, `bottom_rim`, `outer_rim`, `sharp`, `sharp:<deg>`, `boundary`, `all` |
+| Face selectors (`extrude`, `inset`, `mat`) | `top`, `bottom`, `front`, `back`, `left`, `right`, `sides`, `all` |
-## Progressive Tier-1 `spec_topic` domains
+## Progressive `spec_topic` domains
-Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `getSpecTopic(name)`, or MCP `inspect({ topic })`.
+Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `GET /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=...)` |
+| `deform` | `deform` | `solidify(t, offset=-1.0, open_top=false)`, `deform("bend"\|"twist"\|"taper", axis=, angle=, factor=, subdivs=)`, `deform("curve", path=, axis=)`, `deform("lattice", corners=[8 Vec3 points in (x,y,z) bit order])` |
+| `curves` | `curves` | `bezier([(x,y,z), ...], segs=24)`, `nurbs([(x,y,z), ...], degree=3, segs=32, weights=)`, `extrude2d(outer, z0, z1, holes=...)`, `sweep(profile2d, path3d, scale_end=1.0, twist=0.0, closed=false)` |
| `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). |
+| `remesh` | `remesh` | `remesh(voxel_size=0.0)` (`0` = auto `diag/28`), `bisect(normal=(0,0,1), offset=0.0, clear_inner=false)`, `load("path.glb\|obj\|stl", yup=)` |
+| `scene` | `scene` | Multi-object scene graph export & rendering (`--scene` in CLI, `scene: true` in MCP `export` for `.glb`, `.blend`, `.png`, and `.svg`, `exportSceneBytes()` in JS/TS); `_`-prefixed locals and `del("name")`. |
## Invariant metrics (`MeshInvariants`)
@@ -96,6 +100,6 @@ Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `getS
| 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`). |
+| PNG preview | `.png` | Export | Scale-invariant framed view | Pure-Rust software rasterizer (4-view `quad` default; single views on native CLI); supports `--scene` / `scene: true` to render all named parts together with materials. |
+| SVG blueprint | `.svg` | Export | Dimensioned in model units | 3-view orthographic engineering drawing; supports `--scene` / `scene: true` for multi-part scenes. |
+| Blender file | `.blend` | Export (CLI & MCP) | Scaled to meters via glTF bridge | Invokes local Blender (`BLENDER_BIN` or `blender` on `PATH`); supports `--scene` / `scene: true`. |
diff --git a/docs/showcase.html b/docs/showcase.html
index d8910ea..0633ae0 100644
--- a/docs/showcase.html
+++ b/docs/showcase.html
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="utf-8"/>
-<title>Forma v0.4 — The 1.2 MB Pure-Rust 3D Engine Built for AI Agents</title>
+<title>Forma v0.4.2 — Pure-Rust 3D Polyhedral Engine Built for AI Agents</title>
<style>
:root { --bg:#0b1020; --panel:#131b30; --border:#24324d; --text:#f1f5f9; --muted:#94a3b8; --cyan:#38bdf8; --mint:#34d399; --gold:#fbbf24; }
* { box-sizing:border-box; }
@@ -27,15 +27,15 @@
</head>
<body>
<header>
- <h1><span>FORMA</span> v0.4 — Watertight 3D Built for AI</h1>
- <div class="sub">A clean-room, 1.2 MB pure-Rust B-rep modeling engine, Unix CLI, 789-token MCP server, GBNF grammar, and 20 KB pure-Rust studio renderer—89× faster and 800× smaller than headless Blender.</div>
+ <h1><span>FORMA</span> v0.4.2 — Watertight 3D Built for AI</h1>
+ <div class="sub">A ~1.7 MB native (~0.8 MB WASM) pure-Rust polyhedral modeling engine, Unix CLI, 723-token MCP server, GBNF grammar, and zero-GPU studio renderer — ~77×–89× faster and ~530× smaller than headless Blender.</div>
<div class="pills">
- <div class="pill">1.2 MB Static Binary</div>
- <div class="pill">14.7 ms Cold-Start GLB</div>
+ <div class="pill">~1.7 MB Native · ~0.8 MB WASM</div>
+ <div class="pill">16.9 ms Cold-Start GLB</div>
<div class="pill">5.4 ms 5-Hole Batch Flange</div>
<div class="pill">12/12 Models Beat bpy</div>
- <div class="pill">789-Token MCP Schema</div>
- <div class="pill">GLB · STEP · 3MF · STL · OBJ · SVG · PNG</div>
+ <div class="pill">723-Token MCP Schema</div>
+ <div class="pill">GLB · STEP · 3MF · STL · OBJ · BLEND · SVG · PNG</div>
</div>
</header>
<main>
diff --git a/llms.txt b/llms.txt
index 829ec1b..1e8b364 100644
--- a/llms.txt
+++ b/llms.txt
@@ -4,14 +4,14 @@
## Repository Map
-- [SKILL.md](SKILL.md): Ready-to-use Agent Skill (`name: forma`) with 5-step workflow, full syntax cheat sheet, verified recipes, and troubleshooting
-- [README.md](README.md): Overview, quickstart, npm/CLI/MCP usage, and full 12-model / 10-lab benchmarks
+- [SKILL.md](SKILL.md): Ready-to-use Agent Skill (`name: forma`) with token-efficient workflow, full syntax cheat sheet, verified recipes, and troubleshooting
+- [README.md](README.md): Overview, quickstart, npm/CLI/MCP usage, and full 12-model / 9-lab benchmarks
- [AGENTS.md](AGENTS.md): Step-by-step integration guide for AI agents (MCP, CLI, constrained decoding, feedback loop)
- [grammar/forma_pipe.gbnf](grammar/forma_pipe.gbnf): Formal GBNF grammar for zero-syntax-error constrained decoding (llama.cpp, vLLM, XGrammar)
-- [crates/forma-core](crates/forma-core): Pure-Rust double-precision polyhedral mesh kernel, BVH booleans, bevel, shell, subsurf, loft, thread, sweep, text3d, spatial queries, pure-Rust PNG/SVG renderer, GLB/faceted STEP/3MF/STL/OBJ exporters
+- [crates/forma-core](crates/forma-core): Pure-Rust double-precision polyhedral mesh kernel, BVH booleans, bevel, shell, subsurf, gear, loft, thread, sweep, text3d, spatial queries, pure-Rust PNG/SVG renderer, GLB/faceted STEP/3MF/STL/OBJ exporters
- [crates/forma-lang](crates/forma-lang): `Forma-Pipe` declarative modeling language evaluator
- [crates/forma-cli](crates/forma-cli): `forma` CLI (`eval`, `render`, `draw`, `spec`)
-- [crates/forma-mcp](crates/forma-mcp): `forma-mcp` stdio JSON-RPC 2.0 MCP server (4 tools, 789 o200k tokens)
+- [crates/forma-mcp](crates/forma-mcp): `forma-mcp` stdio JSON-RPC 2.0 MCP server (4 tools, 721 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)
@@ -19,7 +19,7 @@
- [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
+- [docs/EXTENDED_BENCHMARK_REPORT.md](docs/EXTENDED_BENCHMARK_REPORT.md): Full 12-model / 9-lab cross-lab & reasoning-effort scaling study
## Quick Commands
@@ -27,11 +27,11 @@
# Build release binaries (~1.7–1.8 MB stripped native)
cargo build --release
-# Print the concise language spec (~355 tokens) or formal GBNF grammar
+# Print the concise language spec (~485 o200k tokens) or formal GBNF grammar
./target/release/forma spec
./target/release/forma spec --gbnf
-# Evaluate a Forma-Pipe script, verify watertightness, export .glb/.step/.3mf/.stl/.obj/.blend, render 4-view .png, draw .svg blueprint
+# Evaluate a Forma-Pipe script, verify watertightness, export .glb/.step/.3mf/.stl/.obj/.blend, render 4-view .png, draw .svg blueprint (add --scene for multi-part assemblies)
./target/release/forma eval --strict --out part.glb --render preview.png --draw blueprint.svg script.forma
# Run stdio MCP server (4 tools: eval, inspect, tx, export)
@@ -41,7 +41,7 @@ cargo build --release
## Forma-Pipe Language Reference (Z-up; numbers are in your model unit, default meters)
- Units: `units("mm")` (`m|cm|mm|um|in|ft`, default `m`) declares the unit your numbers are in. `.3mf` (`unit=`) and `.step` (`SI_UNIT`/`CONVERSION_BASED_UNIT`) carry it; `.glb` is scaled to metres (glTF is metres); `.stl`/`.obj` have no unit field and keep model units. CLI: `forma eval --unit mm`.
-- Assignment & chaining: `name = expr | op | op` (multi-line `|` supported, math `+ - * / sqrt sin cos asin acos abs pi`, last assigned part exports).
+- Assignment, macros & comprehensions: `name = expr | op | op` (multi-line `|` supported; scalars persist across MCP `eval` calls; `_tmp = ...` stays local and is excluded from `scene.parts` / `scene: true` exports; `del("name")` deletes a named part; `def f(p1, p2=default) = expr`; `[expr for i in range(n)]` with 1/2/3-arg `range`; math `+ - * / sqrt sin cos tan asin acos atan atan2 abs pi`; last assigned part exports).
- Common placement kwargs on primitives: `at=(x,y,z)` or `at=[(x,y,z),...]`, `z0=Z` (rests bottom at Z), `rot=(rx,ry,rz)`.
- Primitives:
- `box(sx, sy, sz, at=, z0=)`
@@ -49,33 +49,36 @@ cargo build --release
- `cone(r0, r1, h, segs=32, axis=z)`
- `pipe(r_out, r_in, h, segs=32, axis=z)`
- `sphere(r, segs=32)` | `torus(R, r, segs=32)`
+ - `gear(teeth, module=1.0, h=1.0, pressure_angle=20, bore=0)` (tooth 0 on `+X`; mesh pair at center dist `m*(z1+z2)/2` with gear 2 rotated `180/z2` deg if `z2` is even, `0` deg if odd)
- `revolve([(r,z), ...], segs=32)` (around Z, auto-closes to `r=0`)
- `arc_tube(center=(x,y,z), rx=, rz=, start=-90, end=90, r=0.08)` (XZ elliptical arc)
- `tube([(x,y,z), ...], r=0.08, closed=false)`
- - `extrude2d([(x,y), ...], z0=0, z1=1)`
+ - `extrude2d([(x,y), ...], z0=0, z1=1, holes=)`
- `loft([(z, [(x,y), ...]), ...], segs=24)` (`segs` 8..128)
- `thread(r_minor, r_major, pitch, turns, segs=28)` (`segs` 12..96)
- `sweep([(x,y), ...], [(x,y,z), ...], closed=false)`
- - `text3d("TEXT", size=0.5, depth=0.1)`
+ - `text3d("TEXT", height=0.5, depth=0.1)` (`size=` alias supported)
+ - `load("path.glb|obj|stl", yup=)` (import mesh or uploaded asset key in `forma-server`)
- Pipeline Ops (`mesh | op(...)` or `op(mesh, ...)`):
- Booleans: `add(b, at=)`, `cut(b, at=)`, `intersect(b)` (batch-accelerated when `at=[...]`)
- - Modeling: `bevel(edges, w, segs=1)` (`vertical|top_rim|bottom_rim|outer_rim|sharp|all`), `shell(t, open_top=true)`, `extrude(faces, d)`, `inset(faces, amt, depth=0)` (`top|bottom|sides`), `subsurf(levels=1, crease=false)`, `mirror(x|y|z)`, `pattern_linear(n, step)` / `array(n, step)`, `pattern_radial(n, r=, axis=z)` / `radial(n, r=, axis=z)`
+ - Modeling: `bevel(edges, w, segs=1)` (`vertical|top_rim|bottom_rim|outer_rim|sharp|all`), `shell(t, open_top=true)`, `extrude(faces, d)`, `inset(faces, amt, depth=0)` (`top|bottom|sides|all`), `subsurf(levels=1, crease=false)`, `mirror(x|y|z)`, `pattern_linear(n, step)` / `array(n, step)`, `pattern_radial(n, r=, axis=z)` / `radial(n, r=, axis=z)`, `decimate(ratio=0.5, faces=)`, `remesh(voxel_size=0.0)`
- Placement: `move(x,y,z)`, `rot(rx,ry,rz)`, `scale(sx,sy,sz)`, `align(x|y|z, min|center|max, val)`, `on(base, gap=0)`, `align_z0(z)`
- Materials: `mat(name, color=(r,g,b), metallic=0.1, roughness=0.5, faces=)`, `color(r,g,b)`
-- Spatial Queries (emitted in compact observation output):
+- Spatial Queries & State (emitted in compact observation output):
- `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
+ - `del("name")` — remove a named part from `scene.parts`
## 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`).
+- **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 `< 5 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)
+## MCP Tools (`forma-mcp`, 721 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).
-2. `inspect({})` — Return current scene summary without mutating state.
-3. `tx({ action: "checkpoint"|"rollback"|"undo"|"reset", tag? })` — Instant O(1) copy-on-write state control.
-4. `export({ path, part?, size? })` — Export to `.glb` (PBR + UVs), `.step`, `.3mf`, `.stl`, `.obj`, or render a 4-view `.png` preview.
+1. `eval({ code, strict? })` — Run transactional Forma-Pipe code (auto-rollback on error; scalar variables persist across calls); returns compact ~100-token diff (`V`, `F`, `WT`, `NM`, `B`, `g` genus, `vol`, `bbox`, `size`, tags, query results).
+2. `inspect({ topic? })` — Return current scene summary without mutating state, or an on-demand domain spec (`deform|curves|uv|remesh|scene`).
+3. `tx({ action: "checkpoint"|"rollback"|"undo"|"reset", tag? })` — Instant O(1) copy-on-write state control (snapshots both geometry and scalar variables).
+4. `export({ path, part?, scene?, size? })` — Export to `.glb` (PBR + UVs), `.step`, `.3mf`, `.stl`, `.obj`, `.svg` blueprint, `.blend` (via Blender bridge), or render a 4-view `.png` preview (`scene: true` exports/renders all named parts together for `.glb`, `.blend`, `.png`, and `.svg`).