A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
feat(mcp,core,lang,wasm): MCP AX ergonomics, actionable boolean diagnostics, and AX eval harness
wrong-nebulafe7387ef3768
diff --git a/AGENTS.md b/AGENTS.mdindex abf8957..873d194 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 **900 `o200k` tokens** (including the full 485-token `Forma-Pipe` syntax spec), with full Native ↔ WASM (`forma-3d-mcp`) parity and optional `--log <path>` / `FORMA_MCP_LOG` JSONL session journaling.+`forma-mcp` is a stateful stdio JSON-RPC 2.0 server with **4 tools** totaling **~1,000 `o200k` tokens** (including the compact `Forma-Pipe` syntax spec and advertised topic ops), with full Native ↔ WASM (`forma-3d-mcp`) parity, automatic zero-token-when-clean lint on `eval`, and optional `--log <path>` / `FORMA_MCP_LOG` JSONL session journaling.Build the binary once:```bashdiff --git a/bench/eval_mcp_ax.py b/bench/eval_mcp_ax.pynew file mode 100644index 0000000..0e73bbd--- /dev/null+++ b/bench/eval_mcp_ax.py@@ -0,0 +1,867 @@+#!/usr/bin/env python3+"""End-to-End MCP Agent Experience (AX) Eval Harness for Forma.++Inspired by Firegoat's MCP eval methodology ("What makes a great MCP server?"):+instead of evaluating Forma via CLI code blocks, this harness connects a real+tool-calling agent loop directly to `forma-mcp` (native or WASM) over JSON-RPC+stdio, captures `FORMA_MCP_LOG` traces, and grades every task on:+ - End-to-end pass rate (artifact validity + watertightness + clean lint + no stale exports)+ - Total tokens per passing task (prompt + completion across all turns)+ - Turn count, MCP tool breakdown, `inspect(topic=...)` detours, tool errors+ - MCP bailout rate (how often the agent reaches for a fallback `bash` tool)++Modes:+ # Offline deterministic self-test (no API key needed; verifies all 5 tasks + graders via real MCP):+ python3 bench/eval_mcp_ax.py --self-test --server target/debug/forma-mcp++ # Live single-server run via OpenRouter:+ python3 bench/eval_mcp_ax.py --model anthropic/claude-haiku-5.5 --server target/release/forma-mcp++ # Paired A/B run comparing two MCP servers (e.g., native vs WASM, or old vs new binary):+ python3 bench/eval_mcp_ax.py --model anthropic/claude-haiku-5.5 \\+ --server-a "target/release/forma-mcp" --label-a native \\+ --server-b "node bin/forma-mcp.mjs" --label-b wasm+"""+from __future__ import annotations++import argparse+import json+import os+import shlex+import statistics+import struct+import subprocess+import sys+import tempfile+import time+import urllib.error+import urllib.request+from dataclasses import asdict, dataclass, field+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional, Tuple++REPO_ROOT = Path(__file__).resolve().parent.parent+sys.path.insert(0, str(REPO_ROOT / "tests" / "e2e"))+import helpers as e2e_helpers # noqa: E402++RESULTS_DIR = REPO_ROOT / "bench" / "results"+DEFAULT_OUT = RESULTS_DIR / "mcp_ax_trials.jsonl"++SYSTEM_PROMPT_MCP_AX = (+ "You are a precision 3D CAD agent connected to the Forma MCP server (`eval`, `inspect`, `tx`, `export`). "+ "Complete the user's 3D modeling task accurately in as few turns as possible using the Forma MCP tools. "+ "Ensure all requested files are written to disk, watertight, free of lint defects, and up-to-date "+ "(no stale renders or exports after your final edit). When finished, summarize what you built."+)+++@dataclass+class AxTask:+ task_id: str+ title: str+ prompt: str+ setup: Callable[[Path], None]+ grade: Callable[[Path, List[Dict[str, Any]], Dict[str, Any]], Tuple[bool, List[str]]]+ oracle_calls: Callable[[Path], List[Tuple[str, Dict[str, Any]]]]+++@dataclass+class AxTrialResult:+ arm: str+ model: str+ task_id: str+ passed: bool+ reasons: List[str]+ schema_tokens: int+ prompt_tokens: int+ completion_tokens: int+ total_tokens: int+ cost_usd: float+ turns: int+ mcp_calls: int+ eval_calls: int+ inspect_calls: int+ inspect_topic_calls: int+ tx_calls: int+ export_calls: int+ mcp_errors: int+ bailout_calls: int+ stale_render_end: bool+ stale_export_end: bool+ wall_ms: float+ tool_breakdown: Dict[str, int] = field(default_factory=dict)+++def _check_glb(path: Path) -> Tuple[bool, str]:+ if not path.is_file():+ return False, f"missing GLB '{path.name}'"+ data = path.read_bytes()+ if len(data) < 100 or data[:4] != b"glTF":+ return False, f"invalid GLB header/size in '{path.name}' ({len(data)} bytes)"+ return True, ""+++def _check_png(path: Path) -> Tuple[bool, str]:+ if not path.is_file():+ return False, f"missing PNG '{path.name}'"+ data = path.read_bytes()+ if len(data) < 200 or data[:8] != b"\x89PNG\r\n\x1a\n":+ return False, f"invalid PNG header/size in '{path.name}' ({len(data)} bytes)"+ return True, ""+++def _check_svg(path: Path) -> Tuple[bool, str]:+ if not path.is_file():+ return False, f"missing SVG '{path.name}'"+ txt = path.read_text(encoding="utf-8", errors="replace")+ if "<svg" not in txt or len(txt) < 200:+ return False, f"invalid SVG '{path.name}'"+ return True, ""+++def _check_step(path: Path) -> Tuple[bool, str]:+ if not path.is_file():+ return False, f"missing STEP '{path.name}'"+ txt = path.read_text(encoding="utf-8", errors="replace")+ if "ISO-10303-21;" not in txt:+ return False, f"invalid STEP '{path.name}'"+ return True, ""+++def _write_ascii_stl_box(path: Path, sx: float = 2.0, sy: float = 2.0, sz: float = 2.0) -> None:+ """Write a watertight binary STL box centered at origin for import/bisect tests."""+ hx, hy, hz = sx / 2.0, sy / 2.0, sz / 2.0+ v = [+ (-hx, -hy, -hz), (hx, -hy, -hz), (hx, hy, -hz), (-hx, hy, -hz),+ (-hx, -hy, hz), (hx, -hy, hz), (hx, hy, hz), (-hx, hy, hz),+ ]+ tris = [+ # bottom (-Z)+ (0, 2, 1), (0, 3, 2),+ # top (+Z)+ (4, 5, 6), (4, 6, 7),+ # front (-Y)+ (0, 1, 5), (0, 5, 4),+ # back (+Y)+ (2, 3, 7), (2, 7, 6),+ # left (-X)+ (0, 4, 7), (0, 7, 3),+ # right (+X)+ (1, 2, 6), (1, 6, 5),+ ]+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("wb") as f:+ f.write(b"forma_ax_test_box".ljust(80, b"\x00"))+ f.write(struct.pack("<I", len(tris)))+ for i0, i1, i2 in tris:+ p0, p1, p2 = v[i0], v[i1], v[i2]+ e1 = (p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2])+ e2 = (p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2])+ nx = e1[1] * e2[2] - e1[2] * e2[1]+ ny = e1[2] * e2[0] - e1[0] * e2[2]+ nz = e1[0] * e2[1] - e1[1] * e2[0]+ ln = (nx * nx + ny * ny + nz * nz) ** 0.5 or 1.0+ f.write(struct.pack("<3f3f3f3fH", nx / ln, ny / ln, nz / ln, *p0, *p1, *p2, 0))+++def _grade_common(+ journal: List[Dict[str, Any]],+ final_inspect: Dict[str, Any],+ *,+ min_parts: int = 1,+ require_clean_lint: bool = True,+ require_fresh_sync: bool = True,+) -> List[str]:+ errs: List[str] = []+ if not journal:+ errs.append("no MCP tool calls recorded")+ return errs+ if require_fresh_sync:+ last = journal[-1]+ if last.get("stale_render"):+ errs.append("session ended with stale_render=true")+ if last.get("stale_export"):+ errs.append("session ended with stale_export=true")+ inspect_txt = final_inspect.get("inspect_text", "")+ if "WT=BAD" in inspect_txt or "ERR [" in inspect_txt:+ errs.append("final scene has non-watertight/invalid solid")+ parts_count = final_inspect.get("parts_count", 0)+ if parts_count < min_parts:+ errs.append(f"expected >= {min_parts} part(s), got {parts_count}")+ if require_clean_lint:+ lint_txt = final_inspect.get("lint_text", "")+ if final_inspect.get("lint_supported", True):+ if "OK lint: 0 findings" not in lint_txt:+ errs.append(f"final scene failed lint: {lint_txt.splitlines()[0] if lint_txt else 'empty'}")+ return errs+++def build_ax_tasks() -> List[AxTask]:+ """5 end-to-end MCP AX tasks covering Firegoat's findings on Forma."""++ # T1: Multi-part assembly + nested output directory + clean contacts+ def t1_grade(wd: Path, journal: List[Dict[str, Any]], final: Dict[str, Any]) -> Tuple[bool, List[str]]:+ errs = _grade_common(journal, final, min_parts=3)+ for ok, msg in [+ _check_glb(wd / "exports" / "assembly.glb"),+ _check_png(wd / "exports" / "preview.png"),+ ]:+ if not ok:+ errs.append(msg)+ return len(errs) == 0, errs++ def t1_oracle(wd: Path) -> List[Tuple[str, Dict[str, Any]]]:+ return [+ (+ "eval",+ {+ "code": (+ "base = box(4, 4, 0.5, z0=0) | bevel(vertical, 0.2)\n"+ "pillar = cyl(0.6, 2.0, segs=24) | on(base)\n"+ "cap = box(2.4, 2.4, 0.4) | bevel(vertical, 0.15) | on(pillar)"+ ),+ "strict": True,+ "out": [str(wd / "exports" / "assembly.glb"), str(wd / "exports" / "preview.png")],+ "scene": True,+ "size": 256,+ "view": "iso",+ },+ )+ ]++ # T2: Iterative edit + zero stale render/export leaks+ def t2_grade(wd: Path, journal: List[Dict[str, Any]], final: Dict[str, Any]) -> Tuple[bool, List[str]]:+ errs = _grade_common(journal, final, min_parts=2)+ for ok, msg in [+ _check_glb(wd / "out" / "bracket.glb"),+ _check_png(wd / "out" / "bracket.png"),+ ]:+ if not ok:+ errs.append(msg)+ evals = [r for r in journal if r.get("tool") == "eval" and r.get("ok")]+ if len(evals) < 2:+ errs.append(f"expected >= 2 successful eval steps (build + edit), got {len(evals)}")+ return len(errs) == 0, errs++ def t2_oracle(wd: Path) -> List[Tuple[str, Dict[str, Any]]]:+ return [+ (+ "eval",+ {+ "code": (+ "plate = box(4, 2, 0.4, z0=0) | cut(cyl(0.4, 1.0))\n"+ "boss = cyl(0.7, 0.8, segs=24) | on(plate) | cut(cyl(0.4, 2.0, at=(0, 0, 0.8)))"+ ),+ "out": [str(wd / "out" / "bracket.glb"), str(wd / "out" / "bracket.png")],+ "scene": True,+ "size": 128,+ },+ ),+ (+ "eval",+ {+ "code": "plate = box(4, 2, 0.4, z0=0) | cut(cyl(0.6, 1.0))",+ "out": [str(wd / "out" / "bracket.glb"), str(wd / "out" / "bracket.png")],+ "scene": True,+ "size": 128,+ },+ ),+ ]++ # T3: Hidden-topic capability discovery (load external STL + bisect)+ def t3_setup(wd: Path) -> None:+ _write_ascii_stl_box(wd / "input_block.stl", 2.0, 2.0, 2.0)++ def t3_grade(wd: Path, journal: List[Dict[str, Any]], final: Dict[str, Any]) -> Tuple[bool, List[str]]:+ errs = _grade_common(journal, final, min_parts=1)+ for ok, msg in [+ _check_glb(wd / "out" / "sliced.glb"),+ _check_png(wd / "out" / "sliced.png"),+ ]:+ if not ok:+ errs.append(msg)+ txt = final.get("inspect_text", "")+ if "size=[2.00,2.00,1.00]" not in txt and "vol=4.000" not in txt:+ errs.append(f"expected half-block volume ~4.000 / height 1.00 after bisect, got:\n{txt}")+ return len(errs) == 0, errs++ def t3_oracle(wd: Path) -> List[Tuple[str, Dict[str, Any]]]:+ stl = (wd / "input_block.stl").as_posix()+ return [+ (+ "eval",+ {+ "code": f'sliced = load("{stl}") | bisect(normal=(0, 0, 1), offset=0.0, clear_inner=true)',+ "out": [str(wd / "out" / "sliced.glb"), str(wd / "out" / "sliced.png")],+ "size": 128,+ "view": "iso",+ },+ )+ ]++ # T4: Curved sweep along a 3D Bezier path (curves topic)+ def t4_grade(wd: Path, journal: List[Dict[str, Any]], final: Dict[str, Any]) -> Tuple[bool, List[str]]:+ errs = _grade_common(journal, final, min_parts=1)+ for ok, msg in [+ _check_glb(wd / "out" / "duct.glb"),+ _check_png(wd / "out" / "duct.png"),+ ]:+ if not ok:+ errs.append(msg)+ return len(errs) == 0, errs++ def t4_oracle(wd: Path) -> List[Tuple[str, Dict[str, Any]]]:+ return [+ (+ "eval",+ {+ "code": (+ "p = bezier([(0,0,0), (0,0,1.5), (1.5,0,2.5), (3,0,2.5)], segs=20)\n"+ "duct = sweep([(-0.25,-0.25), (0.25,-0.25), (0.25,0.25), (-0.25,0.25)], p, scale_end=0.7)"+ ),+ "out": [str(wd / "out" / "duct.glb"), str(wd / "out" / "duct.png")],+ "size": 128,+ "view": "iso",+ },+ )+ ]++ # T5: Multi-part assembly in mm + single-part feature inspection + multi-format batch export+ def t5_grade(wd: Path, journal: List[Dict[str, Any]], final: Dict[str, Any]) -> Tuple[bool, List[str]]:+ errs = _grade_common(journal, final, min_parts=2)+ for ok, msg in [+ _check_glb(wd / "out" / "flange_set.glb"),+ _check_step(wd / "out" / "flange_set.step"),+ _check_svg(wd / "out" / "flange_set.svg"),+ _check_png(wd / "out" / "flange_set.png"),+ ]:+ if not ok:+ errs.append(msg)+ insp_part_calls = [+ r for r in journal if r.get("tool") == "inspect" and isinstance(r.get("args"), dict) and r["args"].get("part")+ ]+ if not insp_part_calls:+ errs.append("expected an inspect(part=...) call to verify flange bore/features")+ return len(errs) == 0, errs++ def t5_oracle(wd: Path) -> List[Tuple[str, Dict[str, Any]]]:+ return [+ (+ "eval",+ {+ "code": (+ 'units("mm")\n'+ "flange = box(80, 80, 10, z0=0) | bevel(vertical, 6) | cut(cyl(15, 20, segs=32, at=(0,0,5)))\n"+ "gasket = cyl(32, 4, segs=32) | cut(cyl(15, 8, segs=32)) | on(flange)"+ ),+ "out": [+ str(wd / "out" / "flange_set.glb"),+ str(wd / "out" / "flange_set.step"),+ str(wd / "out" / "flange_set.svg"),+ str(wd / "out" / "flange_set.png"),+ ],+ "scene": True,+ "size": 256,+ "view": "quad",+ },+ ),+ ("inspect", {"part": "flange"}),+ ]++ return [+ AxTask(+ task_id="T1_assembly_clash_fix",+ title="3-part stacked assembly + nested export dir + clean lint",+ prompt=(+ "Build a watertight 3-part vertical assembly: a beveled 4x4x0.5 m `base` resting on z=0, "+ "a cylindrical `pillar` (r=0.6, h=2.0) seated flush on top of `base`, and a beveled 2.4x2.4x0.4 m "+ "`cap` seated flush on top of `pillar`. Verify zero interpenetration or gaps, and export the full "+ "assembly to `exports/assembly.glb` and an isometric preview `exports/preview.png`."+ ),+ setup=lambda _wd: None,+ grade=t1_grade,+ oracle_calls=t1_oracle,+ ),+ AxTask(+ task_id="T2_iterative_edit_fresh_export",+ title="Build 2-part bracket, export, then enlarge bore & re-export cleanly",+ prompt=(+ "First, build a 2-part bracket: a 4x2x0.4 m `plate` on z=0 with a center through-hole (r=0.4) "+ "and a hollow cylindrical `boss` (outer r=0.7, inner r=0.4, h=0.8) seated on `plate`. Export both "+ "parts together to `out/bracket.glb` and `out/bracket.png`. "+ "Second, in a follow-up edit, enlarge the center bore of `plate` to r=0.6 and update both "+ "`out/bracket.glb` and `out/bracket.png` so neither artifact is stale."+ ),+ setup=lambda _wd: None,+ grade=t2_grade,+ oracle_calls=t2_oracle,+ ),+ AxTask(+ task_id="T3_hidden_topic_import_bisect",+ title="Import STL block + plane bisect (tests hidden-topic discovery)",+ prompt=(+ "There is a 2x2x2 m cube mesh at `input_block.stl` in the working directory. "+ "Load it directly in Forma, bisect it along the z=0 plane keeping the upper half (z >= 0) "+ "as a watertight solid of height 1.0 m, and export `out/sliced.glb` and `out/sliced.png`."+ ),+ setup=t3_setup,+ grade=t3_grade,+ oracle_calls=t3_oracle,+ ),+ AxTask(+ task_id="T4_curve_sweep_solidify",+ title="3D Bezier tapered square duct sweep",+ prompt=(+ "Create a watertight tapered square duct named `duct` swept along a 3D cubic Bezier curve "+ "from (0,0,0) via (0,0,1.5) and (1.5,0,2.5) to (3,0,2.5), starting with a 0.5x0.5 m square profile "+ "and tapering to scale_end=0.7. Export `out/duct.glb` and `out/duct.png`."+ ),+ setup=lambda _wd: None,+ grade=t4_grade,+ oracle_calls=t4_oracle,+ ),+ AxTask(+ task_id="T5_multipart_blueprint_and_inspect",+ title="mm flange + gasket assembly, single-part inspect, multi-format export",+ prompt=(+ "Modeling in millimetres (`mm`), build an 80x80x10 mm beveled `flange` on z=0 with a 15 mm radius "+ "center bore, and a 4 mm thick circular `gasket` (outer r=32 mm, inner r=15 mm) seated flush on top. "+ "Inspect `flange` alone to verify its bore feature, and export the full multi-part scene to "+ "`out/flange_set.glb`, `out/flange_set.step`, `out/flange_set.svg`, and `out/flange_set.png`."+ ),+ setup=lambda _wd: None,+ grade=t5_grade,+ oracle_calls=t5_oracle,+ ),+ ]+++def _parse_journal(log_path: Path) -> List[Dict[str, Any]]:+ if not log_path.is_file():+ return []+ out: List[Dict[str, Any]] = []+ for line in log_path.read_text(encoding="utf-8").splitlines():+ line = line.strip()+ if line:+ out.append(json.loads(line))+ return out+++def _collect_final_scene_state(mcp: e2e_helpers.McpClient) -> Dict[str, Any]:+ insp = mcp.tools_call("inspect", {})+ lint = mcp.tools_call("inspect", {"lint": True})+ insp_txt = (insp.get("content") or [{}])[0].get("text", "")+ lint_txt = (lint.get("content") or [{}])[0].get("text", "")+ lint_supported = lint_txt.startswith("OK lint:") or lint_txt.startswith("LINT:")+ parts_count = 0+ for tok in insp_txt.splitlines()[0].split() if insp_txt else []:+ if tok.startswith("parts="):+ try:+ parts_count = int(tok.split("=", 1)[1])+ except ValueError:+ pass+ return {+ "inspect_text": insp_txt,+ "lint_text": lint_txt,+ "lint_supported": lint_supported,+ "parts_count": parts_count,+ }+++def _summarize_journal_counts(journal: List[Dict[str, Any]]) -> Dict[str, Any]:+ counts = {"eval": 0, "inspect": 0, "tx": 0, "export": 0}+ inspect_topic = 0+ errors = 0+ for rec in journal:+ t = rec.get("tool", "")+ if t in counts:+ counts[t] += 1+ if t == "inspect" and isinstance(rec.get("args"), dict) and rec["args"].get("topic"):+ inspect_topic += 1+ if not rec.get("ok", True):+ errors += 1+ last = journal[-1] if journal else {}+ return {+ "counts": counts,+ "mcp_calls": len(journal),+ "inspect_topic_calls": inspect_topic,+ "mcp_errors": errors,+ "stale_render_end": bool(last.get("stale_render", False)),+ "stale_export_end": bool(last.get("stale_export", False)),+ }+++def _mcp_tools_to_openai(mcp_tools: List[Dict[str, Any]], include_bailout_bash: bool) -> List[Dict[str, Any]]:+ tools = [+ {+ "type": "function",+ "function": {+ "name": t["name"],+ "description": t.get("description", ""),+ "parameters": t.get("inputSchema", {"type": "object", "properties": {}}),+ },+ }+ for t in mcp_tools+ ]+ if include_bailout_bash:+ tools.append(+ {+ "type": "function",+ "function": {+ "name": "bash",+ "description": "Run a shell command in the task working directory (fallback if MCP tools cannot do the job).",+ "parameters": {+ "type": "object",+ "properties": {"command": {"type": "string"}},+ "required": ["command"],+ },+ },+ }+ )+ return tools+++def _call_openrouter_tools(+ api_key: str,+ model: str,+ messages: List[Dict[str, Any]],+ tools: List[Dict[str, Any]],+ *,+ temperature: float = 0.0,+ max_tokens: int = 4096,+) -> Tuple[Dict[str, Any], Dict[str, Any]]:+ payload = {+ "model": model,+ "messages": messages,+ "tools": tools,+ "tool_choice": "auto",+ "temperature": temperature,+ "max_tokens": max_tokens,+ }+ req = urllib.request.Request(+ "https://openrouter.ai/api/v1/chat/completions",+ data=json.dumps(payload).encode("utf-8"),+ headers={+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ "HTTP-Referer": "https://github.com/wrong-nebula/forma",+ "X-Title": "Forma MCP AX Eval",+ },+ method="POST",+ )+ for attempt in range(3):+ try:+ with urllib.request.urlopen(req, timeout=120) as resp:+ data = json.loads(resp.read().decode("utf-8"))+ choice = data["choices"][0]["message"]+ usage = data.get("usage") or {}+ return choice, usage+ except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError) as e:+ if attempt == 2:+ raise RuntimeError(f"OpenRouter error after 3 attempts: {e}") from e+ time.sleep(2.0 * (attempt + 1))+ raise RuntimeError("unreachable")+++def run_task_trial(+ task: AxTask,+ server_cmd: List[str],+ arm: str,+ *,+ model: str,+ api_key: Optional[str],+ self_test: bool = False,+ max_turns: int = 8,+ include_bailout_bash: bool = True,+ send_vision_images: bool = False,+) -> AxTrialResult:+ t0 = time.perf_counter()+ with tempfile.TemporaryDirectory(prefix=f"forma-ax-{task.task_id}-") as td:+ wd = Path(td)+ task.setup(wd)+ log_path = wd / ".forma_mcp_trace.jsonl"+ cmd = list(server_cmd) + ["--log", str(log_path)]++ prompt_toks = 0+ comp_toks = 0+ cost_usd = 0.0+ turns = 0+ bailout_calls = 0+ client_journal: List[Dict[str, Any]] = []++ with e2e_helpers.McpClient(cmd, cwd=wd, timeout=30.0) as mcp:+ mcp.initialize()+ mcp_tools = mcp.tools_list()+ schema_tokens = e2e_helpers.count_o200k_tokens(mcp_tools)++ if self_test:+ calls = task.oracle_calls(wd)+ turns = len(calls)+ for tool_name, tool_args in calls:+ res = mcp.tools_call(tool_name, tool_args)+ client_journal.append(+ {+ "tool": tool_name,+ "args": tool_args,+ "ok": not bool(res.get("isError", False)),+ "stale_render": False,+ "stale_export": False,+ }+ )+ else:+ assert api_key, "OPENROUTER_API_KEY is required for live eval runs"+ oa_tools = _mcp_tools_to_openai(mcp_tools, include_bailout_bash)+ messages: List[Dict[str, Any]] = [+ {"role": "system", "content": SYSTEM_PROMPT_MCP_AX},+ {"role": "user", "content": task.prompt},+ ]+ for _turn in range(1, max_turns + 1):+ turns += 1+ msg, usage = _call_openrouter_tools(api_key, model, messages, oa_tools)+ prompt_toks += int(usage.get("prompt_tokens") or 0)+ comp_toks += int(usage.get("completion_tokens") or 0)+ cost_usd += float(usage.get("cost") or 0.0)+ messages.append(msg)++ tool_calls = msg.get("tool_calls") or []+ if not tool_calls:+ break++ pending_images: List[str] = []+ for tc in tool_calls:+ fn = tc.get("function") or {}+ fn_name = fn.get("name", "")+ try:+ fn_args = json.loads(fn.get("arguments") or "{}")+ except json.JSONDecodeError as je:+ messages.append(+ {+ "role": "tool",+ "tool_call_id": tc["id"],+ "content": f"ERR: invalid JSON arguments: {je}",+ }+ )+ continue++ if fn_name == "bash":+ bailout_calls += 1+ cmd_str = str(fn_args.get("command") or "")+ p = subprocess.run(+ cmd_str,+ shell=True,+ cwd=str(wd),+ capture_output=True,+ text=True,+ timeout=30,+ )+ out = (p.stdout + ("\n" + p.stderr if p.stderr else "")).strip()+ messages.append(+ {+ "role": "tool",+ "tool_call_id": tc["id"],+ "content": f"[exit={p.returncode}]\n{out[:4000]}",+ }+ )+ continue++ res = mcp.tools_call(fn_name, fn_args)+ blocks = res.get("content") or []+ texts = [b.get("text", "") for b in blocks if b.get("type") == "text"]+ imgs = [b.get("data", "") for b in blocks if b.get("type") == "image" and b.get("data")]+ client_journal.append(+ {+ "tool": fn_name,+ "args": fn_args,+ "ok": not bool(res.get("isError", False)),+ "stale_render": False,+ "stale_export": False,+ }+ )+ if imgs:+ texts.append(f"[{len(imgs)} inline image/png preview(s) attached]")+ if send_vision_images:+ pending_images.extend(imgs)+ messages.append(+ {+ "role": "tool",+ "tool_call_id": tc["id"],+ "content": "\n".join(texts),+ }+ )+ if pending_images and send_vision_images:+ user_content: List[Dict[str, Any]] = [+ {"type": "text", "text": "Inline preview image(s) from the previous Forma MCP call:"}+ ]+ for b64 in pending_images[:2]:+ user_content.append(+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}}+ )+ messages.append({"role": "user", "content": user_content})++ # Read server trace BEFORE grading inspect calls (fall back to client trace for older servers without --log)+ journal = _parse_journal(log_path) or client_journal+ final_state = _collect_final_scene_state(mcp)+ passed, reasons = task.grade(wd, journal, final_state)++ summary = _summarize_journal_counts(journal)+ counts = summary["counts"]+ wall_ms = (time.perf_counter() - t0) * 1000.0+ return AxTrialResult(+ arm=arm,+ model="oracle" if self_test else model,+ task_id=task.task_id,+ passed=passed,+ reasons=reasons,+ schema_tokens=schema_tokens,+ prompt_tokens=prompt_toks,+ completion_tokens=comp_toks,+ total_tokens=prompt_toks + comp_toks,+ cost_usd=round(cost_usd, 6),+ turns=turns,+ mcp_calls=summary["mcp_calls"],+ eval_calls=counts["eval"],+ inspect_calls=counts["inspect"],+ inspect_topic_calls=summary["inspect_topic_calls"],+ tx_calls=counts["tx"],+ export_calls=counts["export"],+ mcp_errors=summary["mcp_errors"],+ bailout_calls=bailout_calls,+ stale_render_end=summary["stale_render_end"],+ stale_export_end=summary["stale_export_end"],+ wall_ms=round(wall_ms, 2),+ tool_breakdown=counts,+ )+++def print_scorecard(results: List[AxTrialResult]) -> None:+ print("\n## Forma MCP AX Eval Scorecard\n")+ print(+ "| Arm | Task | Pass | Turns | MCP Calls | Topic Detours | Errors | Bailouts | Stale | Total Tokens | Wall ms |"+ )+ print(+ "|-----|------|------|------:|----------:|--------------:|-------:|---------:|------:|-------------:|--------:|"+ )+ for r in results:+ stale = "YES" if (r.stale_render_end or r.stale_export_end) else "no"+ print(+ f"| {r.arm} | {r.task_id} | {'PASS' if r.passed else 'FAIL'} | {r.turns} | "+ f"{r.mcp_calls} | {r.inspect_topic_calls} | {r.mcp_errors} | {r.bailout_calls} | "+ f"{stale} | {r.total_tokens:,} | {r.wall_ms:.1f} |"+ )+ if not r.passed and r.reasons:+ print(f" -> FAIL reasons ({r.arm}/{r.task_id}): {'; '.join(r.reasons)}")++ arms = sorted({r.arm for r in results})+ print("\n### Per-Arm Summary\n")+ print(+ "| Arm | Schema Toks | Pass Rate | Mean Turns | Mean MCP Calls | Topic Detours | Bailouts | Stale Leaks | Mean Pass Tokens |"+ )+ print(+ "|-----|------------:|----------:|-----------:|---------------:|--------------:|---------:|------------:|-----------------:|"+ )+ for arm in arms:+ sub = [r for r in results if r.arm == arm]+ passed = [r for r in sub if r.passed]+ mean_pass_toks = statistics.mean([r.total_tokens for r in passed]) if passed else 0.0+ stale_leaks = sum(1 for r in sub if r.stale_render_end or r.stale_export_end)+ print(+ f"| {arm} | {sub[0].schema_tokens} | {len(passed)}/{len(sub)} ({100.0*len(passed)/len(sub):.0f}%) | "+ f"{statistics.mean([r.turns for r in sub]):.2f} | "+ f"{statistics.mean([r.mcp_calls for r in sub]):.2f} | "+ f"{sum(r.inspect_topic_calls for r in sub)} | "+ f"{sum(r.bailout_calls for r in sub)} | "+ f"{stale_leaks} | {mean_pass_toks:,.0f} |"+ )+++def _load_api_key() -> Optional[str]:+ if os.environ.get("OPENROUTER_API_KEY"):+ return os.environ["OPENROUTER_API_KEY"].strip()+ env_file = REPO_ROOT / ".env"+ if env_file.is_file():+ for line in env_file.read_text(encoding="utf-8").splitlines():+ line = line.strip()+ if line.startswith("OPENROUTER_API_KEY="):+ return line.split("=", 1)[1].strip().strip('"').strip("'")+ return None+++def _resolve_server_cmd(cmd_str: str) -> List[str]:+ """Resolve repo-relative executable or script paths so commands work from temp task directories."""+ parts = shlex.split(cmd_str)+ resolved: List[str] = []+ for p in parts:+ cand = REPO_ROOT / p+ if not Path(p).is_absolute() and cand.exists():+ resolved.append(str(cand.resolve()))+ else:+ resolved.append(p)+ return resolved+++def main() -> int:+ ap = argparse.ArgumentParser(description="Forma MCP Agent Experience (AX) Eval Harness")+ ap.add_argument("--self-test", action="store_true", help="Run offline deterministic oracle calls against MCP server(s)")+ ap.add_argument("--model", default="anthropic/claude-haiku-5.5", help="OpenRouter model slug for live evals")+ ap.add_argument("--server", default=None, help="Single MCP server command (e.g. 'target/debug/forma-mcp')")+ ap.add_argument("--server-a", default=None, help="Arm A MCP server command for A/B eval")+ ap.add_argument("--label-a", default="arm_a", help="Label for Arm A")+ ap.add_argument("--server-b", default=None, help="Arm B MCP server command for A/B eval")+ ap.add_argument("--label-b", default="arm_b", help="Label for Arm B")+ ap.add_argument("--tasks", default=None, help="Comma-separated subset of task IDs to run")+ ap.add_argument("--max-turns", type=int, default=8, help="Max LLM turns per task")+ ap.add_argument("--no-bailout-probe", action="store_true", help="Disable fallback bash tool probe")+ ap.add_argument("--vision", action="store_true", help="Forward inline PNGs as image_url blocks to vision models")+ ap.add_argument("--out", default=str(DEFAULT_OUT), help="Output JSONL path")+ args = ap.parse_args()++ arms: List[Tuple[str, List[str]]] = []+ if args.server_a or args.server_b:+ if args.server_a:+ arms.append((args.label_a, _resolve_server_cmd(args.server_a)))+ if args.server_b:+ arms.append((args.label_b, _resolve_server_cmd(args.server_b)))+ else:+ default_cmd = args.server or str(e2e_helpers.find_forma_mcp_bin())+ arms.append(("forma-mcp", _resolve_server_cmd(default_cmd)))++ tasks = build_ax_tasks()+ if args.tasks:+ wanted = {t.strip() for t in args.tasks.split(",") if t.strip()}+ tasks = [t for t in tasks if t.task_id in wanted]+ if not tasks:+ print(f"No matching tasks in {wanted}", file=sys.stderr)+ return 2++ api_key = None if args.self_test else _load_api_key()+ if not args.self_test and not api_key:+ print("ERR: OPENROUTER_API_KEY not found in env or .env (or pass --self-test)", file=sys.stderr)+ return 2++ all_results: List[AxTrialResult] = []+ out_path = Path(args.out)+ out_path.parent.mkdir(parents=True, exist_ok=True)++ for label, cmd in arms:+ for task in tasks:+ res = run_task_trial(+ task,+ cmd,+ label,+ model=args.model,+ api_key=api_key,+ self_test=args.self_test,+ max_turns=args.max_turns,+ include_bailout_bash=not args.no_bailout_probe,+ send_vision_images=args.vision,+ )+ all_results.append(res)+ with out_path.open("a", encoding="utf-8") as f:+ f.write(json.dumps(asdict(res)) + "\n")++ print_scorecard(all_results)+ return 0 if all(r.passed for r in all_results) else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/bench/results/mcp_ax_ab_live.jsonl b/bench/results/mcp_ax_ab_live.jsonlnew file mode 100644index 0000000..4334991--- /dev/null+++ b/bench/results/mcp_ax_ab_live.jsonl@@ -0,0 +1,10 @@+{"arm": "old_779t", "model": "anthropic/claude-haiku-5.5", "task_id": "T1_assembly_clash_fix", "passed": true, "reasons": [], "schema_tokens": 779, "prompt_tokens": 32009, "completion_tokens": 1610, "total_tokens": 33619, "cost_usd": 0.004006, "turns": 8, "mcp_calls": 11, "eval_calls": 2, "inspect_calls": 3, "inspect_topic_calls": 1, "tx_calls": 0, "export_calls": 6, "mcp_errors": 6, "bailout_calls": 2, "stale_render_end": false, "stale_export_end": false, "wall_ms": 76265.95, "tool_breakdown": {"eval": 2, "inspect": 3, "tx": 0, "export": 6}}+{"arm": "old_779t", "model": "anthropic/claude-haiku-5.5", "task_id": "T2_iterative_edit_fresh_export", "passed": true, "reasons": [], "schema_tokens": 779, "prompt_tokens": 39195, "completion_tokens": 2258, "total_tokens": 41453, "cost_usd": 0.005049, "turns": 8, "mcp_calls": 13, "eval_calls": 3, "inspect_calls": 4, "inspect_topic_calls": 0, "tx_calls": 0, "export_calls": 6, "mcp_errors": 2, "bailout_calls": 1, "stale_render_end": false, "stale_export_end": false, "wall_ms": 18538.97, "tool_breakdown": {"eval": 3, "inspect": 4, "tx": 0, "export": 6}}+{"arm": "old_779t", "model": "anthropic/claude-haiku-5.5", "task_id": "T3_hidden_topic_import_bisect", "passed": true, "reasons": [], "schema_tokens": 779, "prompt_tokens": 27590, "completion_tokens": 1645, "total_tokens": 29235, "cost_usd": 0.003582, "turns": 8, "mcp_calls": 7, "eval_calls": 3, "inspect_calls": 0, "inspect_topic_calls": 0, "tx_calls": 0, "export_calls": 4, "mcp_errors": 3, "bailout_calls": 4, "stale_render_end": false, "stale_export_end": false, "wall_ms": 17321.2, "tool_breakdown": {"eval": 3, "inspect": 0, "tx": 0, "export": 4}}+{"arm": "old_779t", "model": "anthropic/claude-haiku-5.5", "task_id": "T4_curve_sweep_solidify", "passed": true, "reasons": [], "schema_tokens": 779, "prompt_tokens": 16214, "completion_tokens": 1621, "total_tokens": 17835, "cost_usd": 0.002432, "turns": 5, "mcp_calls": 7, "eval_calls": 1, "inspect_calls": 2, "inspect_topic_calls": 2, "tx_calls": 0, "export_calls": 4, "mcp_errors": 2, "bailout_calls": 1, "stale_render_end": false, "stale_export_end": false, "wall_ms": 14455.74, "tool_breakdown": {"eval": 1, "inspect": 2, "tx": 0, "export": 4}}+{"arm": "old_779t", "model": "anthropic/claude-haiku-5.5", "task_id": "T5_multipart_blueprint_and_inspect", "passed": true, "reasons": [], "schema_tokens": 779, "prompt_tokens": 36250, "completion_tokens": 2703, "total_tokens": 38953, "cost_usd": 0.004977, "turns": 8, "mcp_calls": 14, "eval_calls": 4, "inspect_calls": 1, "inspect_topic_calls": 0, "tx_calls": 0, "export_calls": 9, "mcp_errors": 6, "bailout_calls": 1, "stale_render_end": false, "stale_export_end": false, "wall_ms": 34675.69, "tool_breakdown": {"eval": 4, "inspect": 1, "tx": 0, "export": 9}}+{"arm": "new_1006t", "model": "anthropic/claude-haiku-5.5", "task_id": "T1_assembly_clash_fix", "passed": true, "reasons": [], "schema_tokens": 1006, "prompt_tokens": 10396, "completion_tokens": 1750, "total_tokens": 12146, "cost_usd": 0.001915, "turns": 3, "mcp_calls": 3, "eval_calls": 2, "inspect_calls": 1, "inspect_topic_calls": 0, "tx_calls": 0, "export_calls": 0, "mcp_errors": 0, "bailout_calls": 0, "stale_render_end": false, "stale_export_end": false, "wall_ms": 21337.82, "tool_breakdown": {"eval": 2, "inspect": 1, "tx": 0, "export": 0}}+{"arm": "new_1006t", "model": "anthropic/claude-haiku-5.5", "task_id": "T2_iterative_edit_fresh_export", "passed": true, "reasons": [], "schema_tokens": 1006, "prompt_tokens": 20516, "completion_tokens": 2262, "total_tokens": 22778, "cost_usd": 0.003183, "turns": 5, "mcp_calls": 4, "eval_calls": 3, "inspect_calls": 1, "inspect_topic_calls": 1, "tx_calls": 0, "export_calls": 0, "mcp_errors": 0, "bailout_calls": 0, "stale_render_end": false, "stale_export_end": false, "wall_ms": 18411.56, "tool_breakdown": {"eval": 3, "inspect": 1, "tx": 0, "export": 0}}+{"arm": "new_1006t", "model": "anthropic/claude-haiku-5.5", "task_id": "T3_hidden_topic_import_bisect", "passed": true, "reasons": [], "schema_tokens": 1006, "prompt_tokens": 11872, "completion_tokens": 1176, "total_tokens": 13048, "cost_usd": 0.001775, "turns": 4, "mcp_calls": 3, "eval_calls": 2, "inspect_calls": 1, "inspect_topic_calls": 1, "tx_calls": 0, "export_calls": 0, "mcp_errors": 0, "bailout_calls": 0, "stale_render_end": false, "stale_export_end": false, "wall_ms": 10331.23, "tool_breakdown": {"eval": 2, "inspect": 1, "tx": 0, "export": 0}}+{"arm": "new_1006t", "model": "anthropic/claude-haiku-5.5", "task_id": "T4_curve_sweep_solidify", "passed": true, "reasons": [], "schema_tokens": 1006, "prompt_tokens": 8601, "completion_tokens": 1516, "total_tokens": 10117, "cost_usd": 0.001618, "turns": 3, "mcp_calls": 3, "eval_calls": 1, "inspect_calls": 2, "inspect_topic_calls": 1, "tx_calls": 0, "export_calls": 0, "mcp_errors": 0, "bailout_calls": 0, "stale_render_end": false, "stale_export_end": false, "wall_ms": 9913.32, "tool_breakdown": {"eval": 1, "inspect": 2, "tx": 0, "export": 0}}+{"arm": "new_1006t", "model": "anthropic/claude-haiku-5.5", "task_id": "T5_multipart_blueprint_and_inspect", "passed": true, "reasons": [], "schema_tokens": 1006, "prompt_tokens": 19998, "completion_tokens": 2140, "total_tokens": 22138, "cost_usd": 0.00307, "turns": 5, "mcp_calls": 5, "eval_calls": 3, "inspect_calls": 1, "inspect_topic_calls": 0, "tx_calls": 0, "export_calls": 1, "mcp_errors": 0, "bailout_calls": 0, "stale_render_end": false, "stale_export_end": false, "wall_ms": 17100.27, "tool_breakdown": {"eval": 3, "inspect": 1, "tx": 0, "export": 1}}diff --git a/bin/forma-mcp.mjs b/bin/forma-mcp.mjsindex b9f0246..a7d575c 100755--- a/bin/forma-mcp.mjs+++ b/bin/forma-mcp.mjs@@ -1,13 +1,13 @@#!/usr/bin/env node/**- * forma-3d-mcp — Minimal-schema stdio JSON-RPC 2.0 MCP server (4 tools, <800 o200k tokens).+ * forma-3d-mcp — Compact stdio JSON-RPC 2.0 MCP server (4 tools, ~1,000 o200k tokens).* Powered by Forma's bundled pure-Rust WebAssembly engine (zero external dependencies).* Full parity with native `forma-mcp`: fused `eval(out=[...])`, batched `export(paths=[...])`,* named `view`, single-part `inspect(part=...)`, staleness tracking, and `--log`/`FORMA_MCP_LOG`.*/import { readFileSync } from "node:fs";-import { appendFile, mkdir, stat, writeFile } from "node:fs/promises";+import { appendFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";import { dirname, extname } from "node:path";import { performance } from "node:perf_hooks";import { createInterface } from "node:readline";@@ -22,27 +22,34 @@ function buildToolsSchema(specPipe) {return [{name: "eval",- description: `Forma-Pipe; out[] exports.\n${specPipe}`,+ description: `Run Forma-Pipe (strict=true default auto-rolls back; auto-lints; out[] exports + inline PNG).\n${specPipe}`,inputSchema: {type: "object",properties: {code: { type: "string" },strict: { type: "boolean" },- out: { type: "array", items: { type: "string" } },- scene: { type: "boolean" },+ out: {+ type: "array",+ items: { type: "string" },+ description: "Export/render paths (.png returns inline).",+ },+ part: { type: "string" },+ scene: { type: "boolean", description: "All parts." },size: { type: "integer" },- view: { type: "string" },+ view: {+ type: "string",+ enum: ["quad", "front", "back", "right", "left", "top", "iso"],+ },},required: ["code"],},},{name: "inspect",- description: "Invariants, part features, lint, or topic spec.",+ description: "Scene invariants, single-part features, full lint/contacts, or topic spec.",inputSchema: {type: "object",properties: {- part: { type: "string" },topic: {type: "string",enum: ["deform", "curves", "uv", "remesh", "scene"],@@ -55,7 +62,7 @@ function buildToolsSchema(specPipe) {},{name: "tx",- description: "CoW snapshot.",+ description: "CoW snapshot (eval strict=true already auto-rolls back errors).",inputSchema: {type: "object",properties: {@@ -67,7 +74,7 @@ function buildToolsSchema(specPipe) {},{name: "export",- description: "Export .glb/.step/.3mf/.stl/.obj/.svg/.blend/.png.",+ description: "Export .glb/.step/.3mf/.stl/.obj/.svg/.blend/.png (PNGs return inline).",inputSchema: {type: "object",properties: {@@ -145,6 +152,10 @@ function collectExportPaths(args) {}async function exportSinglePath(session, p, { part, isScene, size, view }) {+ const parent = dirname(p);+ if (parent && parent !== ".") {+ await mkdir(parent, { recursive: true });+ }const ext = extname(p).replace(/^\./, "").toLowerCase();if (isScene) {const partsCount = Object.keys(session.inspect().parts ?? {}).length;@@ -202,6 +213,31 @@ async function exportSinglePath(session, p, { part, isScene, size, view }) {];}+function multiPartSingleExportNote(session, part, isScene) {+ if (isScene || part) return null;+ const sync = session.syncStatus();+ const count = Number(sync.parts ?? 0);+ if (count <= 1) return null;+ const last = sync.last_part || "last";+ return `NOTE: exported last part '${last}' only (parts=${count}); pass scene=true for all parts`;+}++async function preloadLocalAssets(session, code) {+ const re = /\b(?:load|import)\s*\(\s*(?:(?:path|file)\s*=\s*)?["']([^"']+)["']/g;+ const seen = new Set();+ for (const m of code.matchAll(re)) {+ const key = m[1].trim();+ if (!key || seen.has(key)) continue;+ seen.add(key);+ try {+ const bytes = await readFile(key);+ session.insertAsset(key, bytes);+ } catch {+ // Let Forma's own load() report missing/invalid files cleanly+ }+ }+}+async function handleToolCall(engine, session, name, args) {try {if (name === "eval") {@@ -210,22 +246,36 @@ async function handleToolCall(engine, session, name, args) {}const outPaths = collectEvalOutPaths(args);const strict = args.strict == null ? true : Boolean(args.strict);+ await preloadLocalAssets(session, args.code);const obs = session.eval(args.code, { strict });+ const lines = [obs.text];+ const critique = session.lint().critique;+ if (typeof critique === "string" && critique.length > 0) {+ lines.push(critique);+ }if (outPaths.length === 0) {- return [false, obs.text, []];+ return [false, lines.join("\n"), []];}- const part = typeof args.part === "string" ? args.part : "";+ const part = typeof args.part === "string" ? args.part.trim() : "";const isScene = args.scene === true;const size = Number.isInteger(args.size) ? args.size : 512;const view =typeof args.view === "string" && args.view.trim().length > 0 ? args.view.trim() : "quad";- const lines = [obs.text];const pngs = [];for (const p of outPaths) {- const [msg, pngBytes] = await exportSinglePath(session, p, { part, isScene, size, view });- lines.push(msg);- if (pngBytes) pngs.push(pngBytes);+ try {+ const [msg, pngBytes] = await exportSinglePath(session, p, { part, isScene, size, view });+ lines.push(msg);+ if (pngBytes) pngs.push(pngBytes);+ } catch (exportErr) {+ const detail = exportErr instanceof Error ? exportErr.message : String(exportErr);+ const rev = session.syncStatus().rev;+ lines.push(`ERR: export '${p}' failed after eval succeeded (scene at r${rev}): ${detail}`);+ return [true, lines.join("\n"), []];+ }}+ const note = multiPartSingleExportNote(session, part, isScene);+ if (note) lines.push(note);return [false, lines.join("\n"), pngs];}if (name === "inspect") {@@ -252,7 +302,7 @@ async function handleToolCall(engine, session, name, args) {}if (name === "export") {const paths = collectExportPaths(args);- const part = typeof args.part === "string" ? args.part : "";+ const part = typeof args.part === "string" ? args.part.trim() : "";const isScene = args.scene === true;const size = Number.isInteger(args.size) ? args.size : 512;const view =@@ -264,6 +314,8 @@ async function handleToolCall(engine, session, name, args) {lines.push(msg);if (pngBytes) pngs.push(pngBytes);}+ const note = multiPartSingleExportNote(session, part, isScene);+ if (note) lines.push(note);return [false, lines.join("\n"), pngs];}return [true, `ERR: unknown tool '${name}' (valid: eval, inspect, tx, export)`, []];diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rsindex 0538eaa..8358cb6 100644--- a/crates/forma-core/src/boolean.rs+++ b/crates/forma-core/src/boolean.rs@@ -2604,11 +2604,150 @@ fn silent_noop_reason(a: &PolyMesh, b: &PolyMesh, op: BoolOp, res: &PolyMesh) ->} else {("add", "added nothing although the tool extends outside the part")};+ let pair_hint = diagnose_boolean_pair(a, b, op)+ .map(|h| format!("; {h}"))+ .unwrap_or_default();Some(format!(- "{name}: {what} (part/tool size ratio {ratio:.1e} is beyond what the boolean tolerance resolves; rescale or split the operation)"+ "{name}: {what} (part/tool size ratio {ratio:.1e} is beyond what the boolean tolerance resolves; rescale or split the operation){pair_hint}"))}+/// Detect coplanar/grazing axis-aligned bounding planes between two boolean operands and return a concrete edit hint.+pub fn diagnose_boolean_pair(a: &PolyMesh, b: &PolyMesh, op: BoolOp) -> Option<String> {+ let (bb_a, bb_b) = (a.aabb(), b.aabb());+ if !bb_a.is_valid() || !bb_b.is_valid() {+ return None;+ }+ let ext = bb_a.max.max(bb_b.max) - bb_a.min.min(bb_b.min);+ let scale = ext.x.max(ext.y).max(ext.z).max(1e-9);+ let tol = 1e-4 * scale;+ let delta = (0.02 * scale).clamp(1e-3, 1.0);+ let axes = ['x', 'y', 'z'];+ let a_min = [bb_a.min.x, bb_a.min.y, bb_a.min.z];+ let a_max = [bb_a.max.x, bb_a.max.y, bb_a.max.z];+ let b_min = [bb_b.min.x, bb_b.min.y, bb_b.min.z];+ let b_max = [bb_b.max.x, bb_b.max.y, bb_b.max.z];+ let mut hits: Vec<String> = Vec::new();+ for k in 0..3 {+ let ax = axes[k];+ if (a_min[k] - b_min[k]).abs() <= tol {+ hits.push(format!("{ax}={:.3} (min)", a_min[k]));+ }+ if (a_max[k] - b_max[k]).abs() <= tol {+ hits.push(format!("{ax}={:.3} (max)", a_max[k]));+ }+ if (a_max[k] - b_min[k]).abs() <= tol {+ hits.push(format!("{ax}={:.3} (tangent)", a_max[k]));+ }+ if (a_min[k] - b_max[k]).abs() <= tol {+ hits.push(format!("{ax}={:.3} (tangent)", a_min[k]));+ }+ }+ if hits.is_empty() {+ return None;+ }+ let action = match op {+ BoolOp::Difference => format!("extend cutter past coplanar face by +{delta:.3}"),+ BoolOp::Union => format!("increase overlap past tangent/coplanar face by +{delta:.3}"),+ BoolOp::Intersect => format!("widen overlap past coplanar face by +{delta:.3}"),+ };+ Some(format!("coplanar/grazing face at {}; {action}", hits.join(", ")))+}++/// Pinpoint offending boundary, non-manifold, or flipped-winding edges on a failed mesh with a centroid and fix hint.+/// Only called on error paths (zero overhead on valid builds).+pub fn diagnose_bad_edges(mesh: &PolyMesh) -> Option<String> {+ if mesh.faces.is_empty() || mesh.verts.is_empty() {+ return None;+ }+ let mut half_edges: Vec<(u32, u32, i8)> = Vec::with_capacity(mesh.faces.len() * 3);+ for f in &mesh.faces {+ let n = f.verts.len();+ for i in 0..n {+ let u = f.verts[i];+ let v = f.verts[(i + 1) % n];+ if u == v || u >= mesh.verts.len() || v >= mesh.verts.len() {+ continue;+ }+ if u < v {+ half_edges.push((u as u32, v as u32, 1));+ } else {+ half_edges.push((v as u32, u as u32, -1));+ }+ }+ }+ if half_edges.is_empty() {+ return None;+ }+ half_edges.sort_unstable_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));++ let mut sum = Vec3::ZERO;+ let mut bad_bb = Aabb::empty();+ let mut bad_count = 0usize;+ let mut i = 0;+ let m = half_edges.len();+ while i < m {+ let (u, v, _) = half_edges[i];+ let mut j = i + 1;+ let mut dir_sum: i32 = half_edges[i].2 as i32;+ while j < m && half_edges[j].0 == u && half_edges[j].1 == v {+ dir_sum += half_edges[j].2 as i32;+ j += 1;+ }+ let count = j - i;+ if count != 2 || dir_sum != 0 {+ let pu = mesh.verts[u as usize];+ let pv = mesh.verts[v as usize];+ if pu.is_finite() && pv.is_finite() {+ sum = sum + (pu + pv) * 0.5;+ bad_bb.include(pu);+ bad_bb.include(pv);+ bad_count += 1;+ }+ }+ i = j;+ }+ if bad_count == 0 || !bad_bb.is_valid() {+ return None;+ }+ let centroid = sum * (1.0 / bad_count as f64);+ let span = bad_bb.size();+ let mesh_ext = mesh.aabb().size();+ let scale = mesh_ext.x.max(mesh_ext.y).max(mesh_ext.z).max(1e-9);+ let plane_tol = 1e-4 * scale;+ let delta = (0.02 * scale).clamp(1e-3, 1.0);++ let plane_hint = if span.z <= plane_tol && (span.x > plane_tol || span.y > plane_tol) {+ Some(format!(+ "coplanar at z={:.3}; extend cutter/overlap past z={:.3} by +{delta:.3}",+ centroid.z, centroid.z+ ))+ } else if span.x <= plane_tol && (span.y > plane_tol || span.z > plane_tol) {+ Some(format!(+ "coplanar at x={:.3}; extend cutter/overlap past x={:.3} by +{delta:.3}",+ centroid.x, centroid.x+ ))+ } else if span.y <= plane_tol && (span.x > plane_tol || span.z > plane_tol) {+ Some(format!(+ "coplanar at y={:.3}; extend cutter/overlap past y={:.3} by +{delta:.3}",+ centroid.y, centroid.y+ ))+ } else {+ None+ };++ match plane_hint {+ Some(ph) => Some(format!(+ "at ({:.3}, {:.3}, {:.3}) [{bad_count} bad edges, {ph}]",+ centroid.x, centroid.y, centroid.z+ )),+ None => Some(format!(+ "at ({:.3}, {:.3}, {:.3}) [{bad_count} bad edges, span=[{:.3},{:.3},{:.3}]]; extend cutter/overlap by +{delta:.3} or nudge seam slightly",+ centroid.x, centroid.y, centroid.z, span.x, span.y, span.z+ )),+ }+}+/// Looks for a surface sample of `probe` (vertices and face centroids) that is decisively inside/// (`want_inside`) or outside `container`: on the wanted side and at least 0.1% of the probe's/// thinnest dimension away from the container's surface, so touching or coincident surfaces@@ -3512,40 +3651,46 @@ pub const SELF_INTERSECTION_BUDGET: u64 = 40_000_000;/// `has_self_intersections` with a work budget (candidate triangle pairs visited). Returns/// `Unverified` when the budget runs out before the mesh could be cleared.pub fn check_self_intersections(mesh: &PolyMesh, budget: u64) -> OverlapCheck {+ check_self_intersections_with_witness(mesh, budget).0+}++/// Same as [`check_self_intersections`], also returning the world-space midpoint of the first+/// self-intersecting triangle pair when `OverlapCheck::Overlap` is found.+pub fn check_self_intersections_with_witness(mesh: &PolyMesh, budget: u64) -> (OverlapCheck, Option<Vec3>) {// World axes first; thin diagonal geometry that defeats axis-aligned boxes gets fast// probes in the dominant edge frame and deterministic fallback frames before spending the// full budget.let probe = budget.min(OVERLAP_WORLD_BUDGET);let first = self_intersection_pass(mesh, None, probe);- if first != OverlapCheck::Unverified || budget <= OVERLAP_WORLD_BUDGET {+ if first.0 != OverlapCheck::Unverified || budget <= OVERLAP_WORLD_BUDGET {return first;}let dom = dominant_edge_frame(mesh);let second = self_intersection_pass(mesh, Some(dom), probe);- if second != OverlapCheck::Unverified {+ if second.0 != OverlapCheck::Unverified {return second;}for fb in fallback_overlap_frames() {let r = self_intersection_pass(mesh, Some(fb), probe);- if r != OverlapCheck::Unverified {+ if r.0 != OverlapCheck::Unverified {return r;}}self_intersection_pass(mesh, Some(dom), budget)}-fn self_intersection_pass(mesh: &PolyMesh, frame: Option<[Vec3; 3]>, budget: u64) -> OverlapCheck {+fn self_intersection_pass(mesh: &PolyMesh, frame: Option<[Vec3; 3]>, budget: u64) -> (OverlapCheck, Option<Vec3>) {let mut work: u64 = 0;if mesh.faces.len() < 2 {- return OverlapCheck::Clear;+ return (OverlapCheck::Clear, None);}let bb = mesh.aabb();if !bb.is_valid() {- return OverlapCheck::Clear;+ return (OverlapCheck::Clear, None);}let extent = bb.size().x.max(bb.size().y).max(bb.size().z);if !extent.is_finite() || extent <= 0.0 {- return OverlapCheck::Clear;+ return (OverlapCheck::Clear, None);}let center = (bb.min + bb.max) * 0.5;let shift = if center.x.abs().max(center.y.abs()).max(center.z.abs()) > 2.0 * extent {@@ -3579,7 +3724,7 @@ fn self_intersection_pass(mesh: &PolyMesh, frame: Option<[Vec3; 3]>, budget: u64}let nt = tris.len();if nt < 2 {- return OverlapCheck::Clear;+ return (OverlapCheck::Clear, None);}let bvh = TriBvh::build(&tris);let mut hits: Vec<u32> = Vec::with_capacity(32);@@ -3590,7 +3735,7 @@ fn self_intersection_pass(mesh: &PolyMesh, frame: Option<[Vec3; 3]>, budget: u64bvh.query_aabb(&ti.aabb, aabb_eps, &mut hits);work = work.saturating_add(hits.len() as u64 + 1);if work > budget {- return OverlapCheck::Unverified;+ return (OverlapCheck::Unverified, None);}for &j_u32 in &hits {let j = j_u32 as usize;@@ -3620,11 +3765,18 @@ fn self_intersection_pass(mesh: &PolyMesh, frame: Option<[Vec3; 3]>, budget: u64continue;}if tris_overlap_3d(ti, tj, 1.0) {- return OverlapCheck::Overlap;+ let witness = (mesh.verts[vi[0]]+ + mesh.verts[vi[1]]+ + mesh.verts[vi[2]]+ + mesh.verts[vj[0]]+ + mesh.verts[vj[1]]+ + mesh.verts[vj[2]])+ * (1.0 / 6.0);+ return (OverlapCheck::Overlap, Some(witness));}}}- OverlapCheck::Clear+ (OverlapCheck::Clear, None)}#[cfg(test)]@@ -3643,4 +3795,46 @@ mod tests {// Within 1e-7 of an edge: in.assert!(point_in_tri_3d(Vec3::new(0.5, -0.5e-7, 0.0), &t) && point_in_tri_3d(Vec3::new(-0.5e-7, 0.0, 0.0), &t));}++ #[test]+ fn actionable_bad_edge_pair_and_self_intersection_diagnostics() {+ // 1. Open box missing top face at z = +0.5 -> pinpoints centroid & coplanar plane+ let mut open_box = crate::primitives::make_box(2.0, 2.0, 1.0, 1);+ open_box.faces.retain(|f| !f.tags.iter().any(|t| t == "top"));+ let bad_diag = diagnose_bad_edges(&open_box).expect("open box must report bad edges");+ assert!(bad_diag.contains("at (0.000, 0.000, 0.500)"), "{bad_diag}");+ assert!(bad_diag.contains("coplanar at z=0.500"), "{bad_diag}");+ assert!(bad_diag.contains("extend cutter/overlap past z=0.500"), "{bad_diag}");++ // Scene::set_part surfaces the diagnostic in InvariantViolation+ let mut scene = crate::scene::Scene::new();+ scene.strict_manifold = true;+ let err = scene.set_part("open", open_box).unwrap_err().to_string();+ assert!(err.contains("invariant violation on 'open'"), "{err}");+ assert!(err.contains("coplanar at z=0.500"), "{err}");++ // 2. Coplanar boolean pair detection+ let plate = crate::primitives::make_box(4.0, 2.0, 0.4, 1);+ let cutter = crate::primitives::make_cylinder(0.5, 0.4, 24, 2);+ let pair_diag = diagnose_boolean_pair(&plate, &cutter, BoolOp::Difference)+ .expect("coplanar caps must be diagnosed");+ assert!(pair_diag.contains("z=-0.200 (min)") && pair_diag.contains("z=0.200 (max)"), "{pair_diag}");+ assert!(pair_diag.contains("extend cutter past coplanar face"), "{pair_diag}");++ // 3. Self-intersecting mesh witness coordinates in Scene::set_part (folded 3-ring loft passes through bottom)+ let sq = vec![(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)];+ let mut pinched = crate::primitives::make_loft(&[(0.0, sq.clone()), (1.0, sq.clone()), (2.0, sq)], 4, 2)+ .expect("loft builds 3-ring box");+ for v in &mut pinched.verts {+ if v.z > 1.5 {+ v.z = -0.5;+ }+ }+ let (ov, witness) = check_self_intersections_with_witness(&pinched, SELF_INTERSECTION_BUDGET);+ assert_eq!(ov, OverlapCheck::Overlap);+ let pt = witness.expect("expected self-intersection witness point");+ assert!(pt.is_finite() && pt.len() < 2.0, "unexpected witness {pt:?}");+ let err2 = scene.set_part("pinched", pinched).unwrap_err().to_string();+ assert!(err2.contains("self-intersecting surface") && err2.contains("near ("), "{err2}");+ }}diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rsindex 24e5565..cbbe8fd 100644--- a/crates/forma-core/src/scene.rs+++ b/crates/forma-core/src/scene.rs@@ -745,10 +745,13 @@ impl Scene {});}if !inv.watertight || !inv.consistent_winding || inv.non_manifold_edges > 0 || inv.nan_verts > 0 {+ let diag = crate::boolean::diagnose_bad_edges(&mesh)+ .map(|d| format!("; {d}"))+ .unwrap_or_default();return Err(SceneError::InvariantViolation {part: name,reason: format!(- "non-manifold result (WT={}, CW={}, NM={}, B={}, NaN={})",+ "non-manifold result (WT={}, CW={}, NM={}, B={}, NaN={}){diag}",inv.watertight,inv.consistent_winding,inv.non_manifold_edges,@@ -792,17 +795,26 @@ impl Scene {});}cached_overlap = Some(overlap);- match crate::boolean::check_self_intersections(&mesh, crate::boolean::SELF_INTERSECTION_BUDGET) {- OverlapCheck::Clear => {+ match crate::boolean::check_self_intersections_with_witness(&mesh, crate::boolean::SELF_INTERSECTION_BUDGET) {+ (OverlapCheck::Clear, _) => {cached_self_ix = Some(OverlapCheck::Clear);}- OverlapCheck::Overlap => {+ (OverlapCheck::Overlap, witness) => {+ let loc = witness+ .filter(|p| p.is_finite())+ .map(|p| {+ format!(+ " near ({:.3}, {:.3}, {:.3}); reduce bevel/shell/solidify thickness or widen overlap/clearance",+ p.x, p.y, p.z+ )+ })+ .unwrap_or_default();return Err(SceneError::InvariantViolation {part: name,- reason: "self-intersecting surface (faces of one shell pass through each other)".into(),+ reason: format!("self-intersecting surface (faces of one shell pass through each other){loc}"),});}- OverlapCheck::Unverified => {+ (OverlapCheck::Unverified, _) => {return Err(SceneError::InvariantViolation {part: name,reason: "self-intersection check exceeded its work budget (mesh too dense to verify; simplify or run without --strict)".into(),diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rsindex 1b7e124..e2af74e 100644--- a/crates/forma-lang/src/lib.rs+++ b/crates/forma-lang/src/lib.rs@@ -79,7 +79,26 @@ add(b,at=) cut(b,at=) intersect(b) mirror(x|y|z) array(n,step) radial(n,r=,axis=bevel(edges,w,segs=1) [vertical|top_rim|bottom_rim|outer_rim|sharp|all] extrude(faces,d) inset(faces,amt,depth=0) [top|bottom|sides|all]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)mat(name,color=(r,g,b[,a]),metallic=0,roughness=0.5,alpha=1,emissive=(r,g,b),transmission=0,double_sided=false) color(r,g,b[,a]) smooth(angle=35) flat() group(path) inst(p,at=,rot=,group=) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z) features(part)-Topics: deform|curves|uv|remesh|scene"#;+Topics (inspect): deform(solidify,deform) curves(bezier,nurbs,sweep) uv(unwrap,decimate) remesh(remesh,bisect,load) scene(group,inst)"#;++/// Compact 1-line usage signature for progressive-topic ops, attached inline on errors to save an `inspect(topic=...)` turn.+pub fn op_usage_hint(name: &str) -> Option<&'static str> {+ match name {+ "solidify" => Some("solidify(t, offset=-1.0, open_top=false)"),+ "deform" => Some("deform(\"bend\"|\"twist\"|\"taper\", axis=x|y|z, angle=45, factor=0.5, subdivs=0) | deform(\"curve\", path=[(x,y,z),...], axis=x|y|z) | deform(\"lattice\", corners=[8 pts])"),+ "bezier" => Some("bezier([(x,y,z),...], segs=24)"),+ "nurbs" | "bspline" => Some("nurbs([(x,y,z),...], degree=3, segs=32, weights=)"),+ "sweep" => Some("sweep(profile2d, path3d, scale_end=1.0, twist=0.0, closed=false)"),+ "unwrap" | "uv" => Some("unwrap(angle=45, margin=0.01)"),+ "decimate" | "lod" => Some("decimate(ratio=0.5, faces=)"),+ "remesh" => Some("remesh(voxel_size=0.0)"),+ "bisect" => Some("bisect(normal=(0,0,1), offset=0.0, clear_inner=false)"),+ "load" | "import" => Some("load(\"path.glb|obj|stl\", yup=)"),+ "group" => Some("group(\"parent/child\") or group(\"parent/child\", [\"a\", \"b\"])"),+ "inst" | "instance" => Some("inst(proto, at=[(x,y,z),...], rot=[(rx,ry,rz),...], scale=, group=, name=)"),+ _ => None,+ }+}/// Progressive on-demand domain specs (loaded only when requested).pub fn spec_topic(topic: &str) -> Result<&'static str, String> {@@ -258,4 +277,28 @@ mod tests {assert!(obs.text.contains("unit=mm"), "{}", obs.text);assert_eq!(s.get_scalar("n"), Some(7.0));}++ #[test]+ fn test_topic_usage_hints_on_error_and_spec_discovery() {+ for op in ["solidify", "deform", "bezier", "nurbs", "sweep", "unwrap", "decimate", "remesh", "bisect", "load"] {+ assert!(SPEC_PIPE.contains(op), "SPEC_PIPE should advertise topic op '{op}'");+ }+ let mut s = Scene::new();+ s.strict_manifold = true;++ let e_solidify = eval_script(&mut s, Dialect::Pipe, "a = box(1,1,1) | solidify()").unwrap_err();+ assert!(e_solidify.contains("(usage: solidify(t, offset=-1.0, open_top=false))"), "{e_solidify}");++ let e_deform = eval_script(&mut s, Dialect::Pipe, "a = box(1,1,1) | deform()").unwrap_err();+ assert!(e_deform.contains("(usage: deform("), "{e_deform}");++ let e_sweep = eval_script(&mut s, Dialect::Pipe, "a = sweep()").unwrap_err();+ assert!(e_sweep.contains("(usage: sweep(profile2d, path3d"), "{e_sweep}");++ let e_bisect = eval_script(&mut s, Dialect::Pipe, "a = box(1,1,1) | bisect(normal=123)").unwrap_err();+ assert!(e_bisect.contains("(usage: bisect(normal=(0,0,1), offset=0.0, clear_inner=false))"), "{e_bisect}");++ let e_load = eval_script(&mut s, Dialect::Pipe, "a = load()").unwrap_err();+ assert!(e_load.contains("(usage: load(\"path.glb|obj|stl\", yup=))"), "{e_load}");+ }}diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rsindex e96d1e8..09f5246 100644--- a/crates/forma-lang/src/pipeline.rs+++ b/crates/forma-lang/src/pipeline.rs@@ -450,6 +450,16 @@ fn unknown_name_hint(name: &str, known: &[&str]) -> String {format!("{suggestion}; accepted: {}", known.join(", "))}+/// Append a compact 1-line usage signature when a progressive-topic op fails so agents can self-correct without an extra `inspect(topic=...)` turn.+fn attach_topic_usage_hint(name: &str, err: String) -> String {+ if let Some(usage) = crate::op_usage_hint(name) {+ if !err.contains("usage:") {+ return format!("{err} (usage: {usage})");+ }+ }+ err+}+fn is_reserved_constant(name: &str) -> bool {matches!(name, "true" | "True" | "false" | "False" | "pi" | "PI")}@@ -1306,6 +1316,18 @@ impl<'a> Parser<'a> {kw: HashMap<String, Val>,arg_names: &ArgNames,line: usize,+ ) -> Result<Val, String> {+ self.eval_call_inner(name, pos, kw, arg_names, line)+ .map_err(|err| attach_topic_usage_hint(name, err))+ }++ fn eval_call_inner(+ &mut self,+ name: &str,+ pos: Vec<Val>,+ kw: HashMap<String, Val>,+ arg_names: &ArgNames,+ line: usize,) -> Result<Val, String> {if let Some(mdef) = self.macros.get(name).cloned() {return self.eval_macro_call(name, mdef, pos, kw, line);@@ -1979,6 +2001,18 @@ impl<'a> Parser<'a> {}fn apply_pipe_op(+ &mut self,+ mesh: PolyMesh,+ op_name: &str,+ pos: Vec<Val>,+ kw: HashMap<String, Val>,+ line: usize,+ ) -> Result<PolyMesh, String> {+ self.apply_pipe_op_inner(mesh, op_name, pos, kw, line)+ .map_err(|err| attach_topic_usage_hint(op_name, err))+ }++ fn apply_pipe_op_inner(&mut self,mut mesh: PolyMesh,op_name: &str,diff --git a/crates/forma-mcp/src/main.rs b/crates/forma-mcp/src/main.rsindex c4888d8..5f68603 100644--- a/crates/forma-mcp/src/main.rs+++ b/crates/forma-mcp/src/main.rs@@ -1,4 +1,4 @@-//! forma-mcp: Minimal-schema stdio JSON-RPC 2.0 MCP server (<800 o200k tokens across 4 tools).+//! forma-mcp: Compact stdio JSON-RPC 2.0 MCP server (~1,000 o200k tokens across 4 tools).//!//! Tools://! 1. `eval` — Execute transactional Forma-Pipe code; returns compact state & spatial diff@@ -74,27 +74,27 @@ fn tools_schema() -> Value {json!([{"name": "eval",- "description": format!("Forma-Pipe; out[] exports.\n{SPEC_PIPE}"),+ "description": format!("Run Forma-Pipe (strict=true default auto-rolls back; auto-lints; out[] exports + inline PNG).\n{SPEC_PIPE}"),"inputSchema": {"type": "object","properties": {"code": { "type": "string" },"strict": { "type": "boolean" },- "out": { "type": "array", "items": { "type": "string" } },- "scene": { "type": "boolean" },+ "out": { "type": "array", "items": { "type": "string" }, "description": "Export/render paths (.png returns inline)." },+ "part": { "type": "string" },+ "scene": { "type": "boolean", "description": "All parts." },"size": { "type": "integer" },- "view": { "type": "string" }+ "view": { "type": "string", "enum": ["quad", "front", "back", "right", "left", "top", "iso"] }},"required": ["code"]}},{"name": "inspect",- "description": "Invariants, part features, lint, or topic spec.",+ "description": "Scene invariants, single-part features, full lint/contacts, or topic spec.","inputSchema": {"type": "object","properties": {- "part": { "type": "string" },"topic": {"type": "string","enum": ["deform", "curves", "uv", "remesh", "scene"],@@ -107,7 +107,7 @@ fn tools_schema() -> Value {},{"name": "tx",- "description": "CoW snapshot.",+ "description": "CoW snapshot (eval strict=true already auto-rolls back errors).","inputSchema": {"type": "object","properties": {@@ -119,7 +119,7 @@ fn tools_schema() -> Value {},{"name": "export",- "description": "Export .glb/.step/.3mf/.stl/.obj/.svg/.blend/.png.",+ "description": "Export .glb/.step/.3mf/.stl/.obj/.svg/.blend/.png (PNGs return inline).","inputSchema": {"type": "object","properties": {@@ -207,6 +207,9 @@ fn export_single_path(view: &str,) -> Result<(String, Option<Vec<u8>>), String> {let path = PathBuf::from(p);+ if let Some(parent) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) {+ std::fs::create_dir_all(parent).map_err(|e| format!("ERR: {e}"))?;+ }let ext = path.extension().and_then(|s| s.to_str())@@ -296,6 +299,20 @@ fn export_single_path(}}+fn multi_part_single_export_note(scene: &Scene, part: Option<&str>, is_scene: bool) -> Option<String> {+ if is_scene || part.is_some() {+ return None;+ }+ let count = scene.part_names().len();+ if count <= 1 {+ return None;+ }+ let last = scene.last_part_name().unwrap_or("last");+ Some(format!(+ "NOTE: exported last part '{last}' only (parts={count}); pass scene=true for all parts"+ ))+}+fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> ToolCallResult {match name {"eval" => {@@ -311,10 +328,18 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> ToolCallResuOk(obs) => obs,Err(e) => return ToolCallResult::err(format!("ERR: {e}")),};+ let mut lines = vec![obs.text];+ if let Some(crit) = scene.lint(forma_core::LintOptions::default()).critique_text() {+ lines.push(crit);+ }if out_paths.is_empty() {- return ToolCallResult::ok(obs.text);+ return ToolCallResult::ok(lines.join("\n"));}- let part = args.get("part").and_then(|v| v.as_str());+ let part = args+ .get("part")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty());let is_scene = args.get("scene").and_then(|v| v.as_bool()).unwrap_or(false);let size = args.get("size").and_then(|v| v.as_u64()).unwrap_or(512) as usize;let view = args@@ -323,7 +348,6 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> ToolCallResu.map(str::trim).filter(|s| !s.is_empty()).unwrap_or("quad");- let mut lines = vec![obs.text];let mut pngs = Vec::new();for p in &out_paths {match export_single_path(scene, p, part, is_scene, size, view) {@@ -333,9 +357,19 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> ToolCallResupngs.push(bytes);}}- Err(e) => return ToolCallResult::err(e),+ Err(e) => {+ let detail = e.strip_prefix("ERR: ").unwrap_or(&e);+ lines.push(format!(+ "ERR: export '{p}' failed after eval succeeded (scene at r{}): {detail}",+ scene.revision()+ ));+ return ToolCallResult::err(lines.join("\n"));+ }}}+ if let Some(note) = multi_part_single_export_note(scene, part, is_scene) {+ lines.push(note);+ }ToolCallResult::ok_with_pngs(lines.join("\n"), pngs)}"inspect" => {@@ -417,7 +451,11 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> ToolCallResuOk(p) => p,Err(e) => return ToolCallResult::err(e),};- let part = args.get("part").and_then(|v| v.as_str());+ let part = args+ .get("part")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty());let is_scene = args.get("scene").and_then(|v| v.as_bool()).unwrap_or(false);let size = args.get("size").and_then(|v| v.as_u64()).unwrap_or(512) as usize;let view = args@@ -427,7 +465,7 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> ToolCallResu.filter(|s| !s.is_empty()).unwrap_or("quad");- let mut messages = Vec::with_capacity(paths.len());+ let mut messages = Vec::with_capacity(paths.len() + 1);let mut pngs = Vec::new();for p in &paths {match export_single_path(scene, p, part, is_scene, size, view) {@@ -440,6 +478,9 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> ToolCallResuErr(e) => return ToolCallResult::err(e),}}+ if let Some(note) = multi_part_single_export_note(scene, part, is_scene) {+ messages.push(note);+ }ToolCallResult::ok_with_pngs(messages.join("\n"), pngs)}other => ToolCallResult::err(format!(@@ -1193,4 +1234,89 @@ p4 = cyl(0.5, 1, at=(12, 0, 0))";assert!(bad.text.contains("PART_INTERSECTION"), "{}", bad.text);assert!(bad.text.contains("GRAZING_GAP"), "{}", bad.text);}++ #[test]+ fn mcp_ax_auto_lint_nested_dirs_partial_out_and_multipart_note() {+ let schema = tools_schema();+ let tools = schema.as_array().unwrap();+ let eval_tool = tools.iter().find(|t| t["name"] == "eval").unwrap();+ assert_eq!(eval_tool["inputSchema"]["properties"]["part"]["type"], json!("string"));+ assert!(eval_tool["inputSchema"]["properties"]["out"]["description"].as_str().is_some());+ assert_eq!(+ eval_tool["inputSchema"]["properties"]["view"]["enum"],+ json!(["quad", "front", "back", "right", "left", "top", "iso"])+ );++ let tmp_dir = std::env::temp_dir().join(format!("forma-mcp-ax-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&tmp_dir);++ let mut scene = Scene::new();+ // Clean build emits 0 lint lines+ let clean = handle_tool_call(+ &mut scene,+ "eval",+ &json!({ "code": "base = box(3, 3, 1, z0=0) | bevel(vertical, 0.2)\ntop = cyl(0.6, 1.5, segs=24) | on(base)" }),+ );+ assert!(!clean.is_error, "{}", clean.text);+ assert!(!clean.text.contains("lint["), "clean eval must emit 0 lint tokens:\n{}", clean.text);++ // Multi-part single export without scene=true or part emits NOTE + auto-creates nested parent dirs+ let nested_png = tmp_dir.join("nested/dir/preview.png");+ let single_exp = handle_tool_call(+ &mut scene,+ "export",+ &json!({ "path": nested_png.to_str().unwrap(), "size": 64, "view": "iso" }),+ );+ assert!(!single_exp.is_error, "{}", single_exp.text);+ assert!(nested_png.exists(), "nested parent dirs should be auto-created");+ assert!(+ single_exp.text.contains("NOTE: exported last part 'top' only (parts=2); pass scene=true for all parts"),+ "{}",+ single_exp.text+ );++ // Explicit part suppresses the multi-part NOTE+ let explicit_png = tmp_dir.join("nested/dir/base.png");+ let explicit_exp = handle_tool_call(+ &mut scene,+ "export",+ &json!({ "path": explicit_png.to_str().unwrap(), "part": "base", "size": 64 }),+ );+ assert!(!explicit_exp.is_error, "{}", explicit_exp.text);+ assert!(!explicit_exp.text.contains("NOTE: exported last part"), "{}", explicit_exp.text);++ // Defective eval auto-appends compact critique lines directly on eval+ let dirty = handle_tool_call(+ &mut scene,+ "eval",+ &json!({ "code": "clash = box(2, 2, 2, at=(0.5, 0, 0.5))\nfloat = box(1, 1, 1, z0=2.5004)" }),+ );+ assert!(!dirty.is_error, "{}", dirty.text);+ assert!(dirty.text.contains("lint[WARN|PART_INTERSECTION]"), "{}", dirty.text);+ assert!(dirty.text.contains("lint[WARN|GRAZING_GAP]"), "{}", dirty.text);++ // Partial eval(out=[...]) failure preserves obs.text and reports committed revision+ let ok_png = tmp_dir.join("partial/ok.png");+ let bad_ext = tmp_dir.join("partial/bad.xyz");+ let partial = handle_tool_call(+ &mut scene,+ "eval",+ &json!({+ "code": "extra = box(1, 1, 1, at=(10, 0, 0))",+ "out": [ok_png.to_str().unwrap(), bad_ext.to_str().unwrap()],+ "scene": true,+ "size": 64+ }),+ );+ assert!(partial.is_error, "{}", partial.text);+ assert!(ok_png.exists());+ assert!(partial.text.contains("- extra:"), "obs.text should be preserved:\n{}", partial.text);+ assert!(+ partial.text.contains(&format!("failed after eval succeeded (scene at r{})", scene.revision())),+ "{}",+ partial.text+ );++ let _ = std::fs::remove_dir_all(&tmp_dir);+ }}diff --git a/crates/forma-wasm/src/lib.rs b/crates/forma-wasm/src/lib.rsindex d2914a9..1aa801a 100644--- a/crates/forma-wasm/src/lib.rs+++ b/crates/forma-wasm/src/lib.rs@@ -158,6 +158,34 @@ pub extern "C" fn forma_session_free(id: u32) {});}+/// Attach an in-memory binary asset (`.glb`, `.obj`, `.stl`) so `load("name")` works inside WASM.+#[no_mangle]+pub extern "C" fn forma_session_insert_asset(+ id: u32,+ name_ptr: *const u8,+ name_len: usize,+ data_ptr: *const u8,+ data_len: usize,+) -> u32 {+ let name = match unsafe { read_utf8(name_ptr, name_len) } {+ Ok(s) => s,+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),+ };+ let bytes = if data_len == 0 || data_ptr.is_null() {+ Vec::new()+ } else {+ unsafe { std::slice::from_raw_parts(data_ptr, data_len) }.to_vec()+ };+ STATE.with(|st| {+ let mut s = st.borrow_mut();+ let Some(scene) = s.sessions.get_mut(&id) else {+ return s.set_err(format!("invalid session id {id}"));+ };+ scene.insert_asset(name, bytes);+ s.set_ok_str("OK")+ })+}+/// Evaluate script in session; sets result buffer to JSON Observation (or error string)./// dialect: 0 = pipe, 1 = compact.#[no_mangle]@@ -242,6 +270,8 @@ pub extern "C" fn forma_session_sync_status(id: u32) -> u32 {"rev": scene.revision(),"stale_render": scene.is_stale_since_render(),"stale_export": scene.is_stale_since_export(),+ "parts": scene.part_names().len(),+ "last_part": scene.last_part_name(),"text": scene.sync_status(false).unwrap_or_default(),}).to_string();@@ -265,6 +295,7 @@ pub extern "C" fn forma_session_lint(id: u32, include_raw_box: u32) -> u32 {"findings": rep.findings,"contacts": rep.contacts,"text": rep.full_text(),+ "critique": rep.critique_text(),}).to_string();s.set_ok_str(payload)diff --git a/lib/edge.mjs b/lib/edge.mjsindex 504e881..6ab6505 100644--- a/lib/edge.mjs+++ b/lib/edge.mjs@@ -70,14 +70,18 @@ export class FormaEngine {}_withUtf8(str, fn) {+ return this._withBytes(encoder.encode(str ?? ""), fn);+ }++ _withBytes(bytes, fn) {return this._run(() => {- const bytes = encoder.encode(str ?? "");- const ptr = this.exports.forma_alloc(bytes.length);+ const buf = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes ?? 0);+ const ptr = this.exports.forma_alloc(buf.length);try {- if (bytes.length > 0) {- new Uint8Array(this.memory.buffer, ptr, bytes.length).set(bytes);+ if (buf.length > 0) {+ new Uint8Array(this.memory.buffer, ptr, buf.length).set(buf);}- return fn(ptr, bytes.length);+ return fn(ptr, buf.length);} catch (err) {if (typeof WebAssembly !== "undefined" && err instanceof WebAssembly.RuntimeError) {this._trapped = true;@@ -85,7 +89,7 @@ export class FormaEngine {throw err;} finally {if (!this._trapped) {- this.exports.forma_dealloc(ptr, bytes.length);+ this.exports.forma_dealloc(ptr, buf.length);}}});@@ -165,6 +169,17 @@ export class FormaSession {});}+ /** Attach an in-memory binary asset (`.glb`, `.obj`, `.stl`) for `load("name")` calls in WASM. */+ insertAsset(name, bytes) {+ this._checkOpen();+ return this._engine._withUtf8(String(name), (np, nl) =>+ this._engine._withBytes(bytes, (dp, dl) => {+ this._engine.exports.forma_session_insert_asset(this._id, np, nl, dp, dl);+ return this._engine._readResultString();+ })+ );+ }+/** Evaluate Forma-Pipe (or compact) code transactionally; returns parsed Observation. */eval(code, { dialect = "pipe", strict = true, unit } = {}) {this._checkOpen();diff --git a/lib/index.d.ts b/lib/index.d.tsindex 2840521..bc0bc8c 100644--- a/lib/index.d.ts+++ b/lib/index.d.ts@@ -28,6 +28,8 @@ export interface FormaSyncStatus {rev: number;stale_render: boolean;stale_export: boolean;+ parts: number;+ last_part: string | null;text: string;}@@ -50,6 +52,7 @@ export interface FormaLintReport {findings: FormaLintFinding[];contacts: FormaPartContact[];text: string;+ critique: string | null;}export interface FormaInvariants {@@ -182,6 +185,8 @@ export interface TopicOptions {export class FormaSession {/** Set the session model unit (`m`, `cm`, `mm`, `um`, `in`, `ft`). */setUnit(unit: FormaUnit | string): string;+ /** Attach an in-memory binary asset (`.glb`, `.obj`, `.stl`) for `load("name")` calls in WASM. */+ insertAsset(name: string, bytes: Uint8Array): string;/** Evaluate a modeling script transactionally and return invariants + diff. */eval(code: string, opts?: SessionEvalOptions): FormaObservation;/** Inspect current scene invariants without mutating state. */diff --git a/tests/npm_smoke.mjs b/tests/npm_smoke.mjsindex 0d12dc5..717a9f9 100644--- a/tests/npm_smoke.mjs+++ b/tests/npm_smoke.mjs@@ -301,7 +301,7 @@ section(flange, 0.0)// 4. MCP stdio server bin/forma-mcp.mjs (full native parity: fused eval+out, batch paths[], view, inspect(part), delta-first, staleness, --log)const mcpGlb = join(tmp, "mcp.glb");const mcpSceneGlb = join(tmp, "mcp-scene.glb");- const mcpPng = join(tmp, "mcp.png");+ const mcpPng = join(tmp, "nested", "mcp.png");const mcpIsoPng = join(tmp, "mcp-iso.png");const mcpSvg = join(tmp, "mcp-scene.svg");const mcpLog = join(tmp, "mcp-session.jsonl");@@ -330,6 +330,9 @@ section(flange, 0.0){ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name: "eval", arguments: { code: "p1 = p1 | bevel(vertical, 0.1)", strict: true } } },{ jsonrpc: "2.0", id: 8, method: "tools/call", params: { name: "export", arguments: { paths: [mcpGlb, mcpPng], size: 256, view: "front" } } },{ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "inspect", arguments: { lint: true } } },+ { jsonrpc: "2.0", id: 10, method: "tools/call", params: { name: "eval", arguments: { code: "clash = box(2,2,2, at=(0.5,0,0))" } } },+ { jsonrpc: "2.0", id: 11, method: "tools/call", params: { name: "eval", arguments: { code: "bad = box(1,1,1) | solidify()" } } },+ { jsonrpc: "2.0", id: 12, method: "tools/call", params: { name: "eval", arguments: { code: "extra = box(1,1,1, at=(12,0,0))", out: [join(tmp, "bad.xyz")], scene: true } } },];const mcpResponses = await new Promise((resolve, reject) => {const child = spawn(process.execPath, [join(ROOT, "bin", "forma-mcp.mjs"), "--log", mcpLog], {@@ -348,17 +351,19 @@ section(flange, 0.0)child.stdin.end();});- assert.equal(mcpResponses.length, 9);+ assert.equal(mcpResponses.length, 12);assert.equal(mcpResponses[1].result.tools.length, 4);- for (let i = 2; i < mcpResponses.length; i++) {+ assert.equal(mcpResponses[1].result.tools[0].inputSchema.properties.part.type, "string");+ for (let i = 2; i <= 9; i++) {assert.equal(mcpResponses[i].result.isError,false,`MCP tool call ${i} unexpectedly errored: ${JSON.stringify(mcpResponses[i])}`);}- // Fused eval + out[] returned text + inline iso PNG+ // Fused eval + out[] returned text + inline iso PNG (and 0 lint tokens on clean scene)assert.ok(mcpResponses[2].result.content[0].text.includes("WT=ok"));+ assert.ok(!mcpResponses[2].result.content[0].text.includes("lint["));assert.ok(mcpResponses[2].result.content[0].text.includes("scene iso preview"));assert.equal(mcpResponses[2].result.content.length, 2);assert.equal(mcpResponses[2].result.content[1].type, "image");@@ -371,9 +376,10 @@ section(flange, 0.0)const incText = mcpResponses[6].result.content[0].text;assert.ok(incText.includes("unchanged(2): p0, p2 (all WT=ok)"), incText);assert.ok(incText.includes("sync: rev=r2 render=r1(stale) export=r1(stale)"), incText);- // Batched export(paths[]) returns inline front PNG and writes GLB+ // Batched export(paths[]) auto-creates nested dirs, returns inline front PNG, and warns about single-part multi-part exportconst pngContent = mcpResponses[7].result.content;assert.equal(pngContent.length, 2, "PNG export must return text + inline MCP image block");+ assert.ok(pngContent[0].text.includes("NOTE: exported last part 'p1' only (parts=3); pass scene=true for all parts"), pngContent[0].text);assert.equal(pngContent[1].type, "image");assert.equal(pngContent[1].mimeType, "image/png");assert.ok(Buffer.from(pngContent[1].data, "base64").subarray(0, 4).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47])));@@ -381,13 +387,23 @@ section(flange, 0.0)// Verify MCP inspect({ lint: true }) reports clean lintconst lintText = mcpResponses[8].result.content[0].text;assert.ok(lintText.includes("OK lint: 0 findings"), lintText);+ // Verify auto-critique piggybacks onto MCP eval when an intersection is introduced+ const clashText = mcpResponses[9].result.content[0].text;+ assert.ok(clashText.includes("lint[WARN|PART_INTERSECTION]"), clashText);+ // Verify progressive-topic op error includes inline usage hint+ assert.equal(mcpResponses[10].result.isError, true);+ assert.ok(mcpResponses[10].result.content[0].text.includes("(usage: solidify(t, offset=-1.0, open_top=false))"), mcpResponses[10].result.content[0].text);+ // Verify partial eval(out=[...]) export failure preserves obs.text and reports committed revision+ assert.equal(mcpResponses[11].result.isError, true);+ const partialText = mcpResponses[11].result.content[0].text;+ assert.ok(partialText.includes("- extra:") && partialText.includes("failed after eval succeeded (scene at r"), partialText);// Verify JSONL session journalconst journal = readFileSync(mcpLog, "utf-8").trim().split("\n").map((l) => JSON.parse(l));- assert.equal(journal.length, 7);+ assert.equal(journal.length, 10);assert.equal(journal[0].rec, "r1");assert.equal(journal[4].stale_render, true);assert.equal(journal[5].stale_render, false);- console.log("PASS 5/5: MCP stdio server bin/forma-mcp.mjs (fused eval+out, batch paths[], view, inspect(part+features), delta-first, staleness, --log)");+ console.log("PASS 5/5: MCP stdio server bin/forma-mcp.mjs (fused eval+out, auto-lint, inline hints, batch paths[], view, inspect(part+features), delta-first, staleness, --log)");} finally {rmSync(tmp, { recursive: true, force: true });}diff --git a/wasm/forma.wasm b/wasm/forma.wasmindex 030eab3..61c45b8 100755Binary files a/wasm/forma.wasm and b/wasm/forma.wasm differ