3D engine that AI agents drive
Add the agent modeling suite and its first baseline
Nguyen Xuan An6081297b68a7
diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.mdnew file mode 100644index 00000000..56576991--- /dev/null+++ b/bench/agent-modeling/README.md@@ -0,0 +1,78 @@+# Agent modeling suite++The suite measures how well an agent models through the 67.js MCP tools. It records how often the agent succeeds and+what each success costs in tool calls, tokens and time. It is the yardstick from the modeling plan: a mesh feature+earns its place only if it raises these numbers.++## Tasks++Each task in `tasks.mjs` is a prompt with sizes in metres plus machine checks. The checks look only at the object the+exported recipe builds, never at how it was built, so a recipe made of primitives and one made with mesh edits are+graded alike. `measure.mjs` measures every node's render triangles in world space and reads lint from the engine's+own mesh report:++- bounds, plus whether the object rests on the ground and is centred;+- connected parts, and lint (closed and consistently wound);+- through holes (genus, from the Euler characteristic of closed parts);+- volume;+- lines through the object: whether a line along an axis misses it (an open pane) or hits it (a bar);+- closed loops where a plane cuts the object. For example, five loops at Y = 0.1 means five posts, and two loops just+ inside a side face means a recessed panel;+- outer tips around the thin axis, such as gear teeth;+- UV texel-density stretch.++| Task | What it exercises |+| --- | --- |+| crate | Insets and extrusions (recessed panels, raised lid) |+| bolt | Primitives or extrude, exact proportions |+| window | Four through holes |+| table | Several parts that stand on the ground |+| mug | A hollow, one-piece object with a handle loop (booleans or solidify) |+| gear | A profile with 12 teeth and a bore |+| fence | Repetition (array) and rails between posts |+| bracket | Two plates and two holes |+| soap | Rounding every edge (bevel) |+| crate-uv | The crate with even UVs |++`references.mjs` holds one hand-built solution per task. `tests/agent-modeling-suite.test.js` checks that every+reference passes and that broken variants fail. That keeps a wrong checker from costing an agent run.++## Running++```sh+node bench/agent-modeling/run.mjs --claude <path to claude> --model sonnet --label baseline+```++Each task gets a fresh non-interactive Claude Code session in an empty temporary folder. The session has only the+67.js MCP server, its built-in file and shell tools are disabled, and it runs under a per-task budget (`--budget`, in+USD, default 3) and timeout (`--timeout`, in seconds, default 1200). Pick tasks with `--tasks crate,bolt`. Raw+transcripts and exported recipes go to `artifacts/agent-modeling/<run>/`. The summary, with the model ID reported by+the session, goes to `results/<run>.json`. Grade one recipe by hand with+`node bench/agent-modeling/check.mjs <task> <recipe.json>`.++`node bench/agent-modeling/regrade.mjs <run>` grades a run's saved recipes again after a checker fix.++Compare runs only when they use the same model and suite version. A single run per task is noisy, so read differences+of one or two tasks as noise.++## Baseline++`results/2026-10-30-07-48-sonnet-baseline.json`: `claude-sonnet-5-5`, one run per task, without the `build-67js-scene` skill, 67.js 0.11.0.+10 of 10 passed with 67 tool calls and $4.76 in total. The `bracket` record comes from a rerun after its prompt was+made unambiguous about the total height; the others were graded again after three checker fixes, without new agent runs.++Read this as a cost baseline, not a success rate:++- **The pass rate is at its ceiling.** Sonnet passes every task at this difficulty, so these tasks can only show changes in+ tool calls and cost. The suite needs harder tasks before it can show that a feature helps an agent succeed.+- **Agents rarely use the edit tools.** Only 2 of 10 runs called `mesh_edit`. Most recipes use placed primitives, and+ the mesh edits they do use are written directly into `scene_create`. No run used `loop_cut`, `mirror` or `array`.++Friction seen in the transcripts:++- `extrude` with holes whose edges line up leaves T-junctions in its caps, so the mesh is open. The window run hit it+ and fell back to separate bars.+- `mesh_inspect` takes `geometries`, while `mesh_edit` takes `geometry`. Four runs sent `geometry` and got a+ validation error.+- The default box has a bevel, which surprised the fence, table and soap runs. They first got rounded shapes or wrong+ sizes.diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjsnew file mode 100644index 00000000..390773ae--- /dev/null+++ b/bench/agent-modeling/check.mjs@@ -0,0 +1,94 @@+// Grades an exported recipe against a task's checks. CLI: node bench/agent-modeling/check.mjs <task-id> <recipe.json>+import { readFile } from 'node:fs/promises';+import { fileURLToPath } from 'node:url';+import { measureRecipe } from './measure.mjs';+import { taskById } from './tasks.mjs';++const AXES = { x: 0, y: 1, z: 2 };+const SIZE_TOLERANCE = 0.03;+const SIZE_FLOOR = 0.003;+const GROUND_TOLERANCE = 0.005;++const round = value => Number(value.toPrecision(4));++function checkOne(check, measures) {+ switch (check.kind) {+ case 'lint':+ return { pass: measures.lintProblems === 0 && measures.closedParts === measures.parts, detail: measures.lintProblems ? measures.problemKinds.join(', ') : `${measures.closedParts}/${measures.parts} parts closed` };+ case 'parts':+ return { pass: measures.parts <= check.max, detail: `${measures.parts} parts` };+ case 'size': {+ const failures = [];+ check.expected.forEach((expected, axis) => {+ if (expected === null) return;+ const allowed = Math.max(expected * SIZE_TOLERANCE, SIZE_FLOOR);+ if (Math.abs(measures.size[axis] - expected) > allowed) failures.push(`${'xyz'[axis]} ${round(measures.size[axis])} vs ${expected}`);+ });+ return { pass: failures.length === 0, detail: failures.join('; ') || measures.size.map(round).join(' x ') };+ }+ case 'extent': {+ const values = check.axes.map(axis => measures.size[AXES[axis]]);+ return { pass: values.every(value => value >= check.min && value <= check.max), detail: values.map(round).join(', ') };+ }+ case 'ground': {+ const centreX = (measures.bounds.min[0] + measures.bounds.max[0]) / 2;+ const centreZ = (measures.bounds.min[2] + measures.bounds.max[2]) / 2;+ const footprint = Math.max(measures.size[0], measures.size[2]);+ // The mug's handle moves its bounds off centre, so that task checks only the ground.+ const centred = check.centred === false || Math.abs(centreX) <= Math.max(0.05 * footprint, SIZE_FLOOR) && Math.abs(centreZ) <= Math.max(0.05 * footprint, SIZE_FLOOR);+ return { pass: Math.abs(measures.bounds.min[1]) <= GROUND_TOLERANCE && centred, detail: `min y ${round(measures.bounds.min[1])}, centre ${round(centreX)}, ${round(centreZ)}` };+ }+ case 'holes':+ return { pass: measures.holes === check.equals, detail: measures.holes === null ? 'not closed' : `${measures.holes} through holes` };+ case 'volume':+ return { pass: measures.volume >= check.min && measures.volume <= check.max, detail: `${round(measures.volume)} m3` };+ case 'section': {+ const loops = measures.section(check.axis, check.at);+ return { pass: loops === check.equals, detail: `${loops} loops at ${check.axis} = ${check.at}` };+ }+ case 'through': {+ const blockedOpen = check.open.filter(point => measures.lineHits(check.axis, point) > 0);+ const missing = check.solid.filter(point => measures.lineHits(check.axis, point) === 0);+ const problems = [...blockedOpen.map(point => `blocked at ${point}`), ...missing.map(point => `missing at ${point}`)];+ return { pass: problems.length === 0, detail: problems.join('; ') || `${check.open.length} open, ${check.solid.length} solid along ${check.axis}` };+ }+ case 'tips':+ return { pass: measures.tips === check.equals, detail: `${measures.tips} tips` };+ case 'triangles':+ return { pass: measures.triangles >= check.min, detail: `${measures.triangles} triangles` };+ case 'uv': {+ const everyPart = measures.uv.parts === measures.uv.of;+ return { pass: everyPart && measures.uv.stretch <= check.maxStretch, detail: everyPart ? `stretch ${round(measures.uv.stretch)}` : `${measures.uv.parts}/${measures.uv.of} nodes have UVs` };+ }+ default:+ throw new TypeError(`Unknown check kind ${check.kind}.`);+ }+}++/** What a recipe was built from, to see which tools agents actually reach for: geometry types and mesh operations. */+export function recipeFeatures(recipe) {+ const geometries = recipe.geometries ?? [];+ const operations = geometries.flatMap(geometry => [...(geometry.edits ?? []), ...(geometry.stack ?? [])].map(edit => edit.op));+ return { geometryTypes: [...new Set(geometries.map(geometry => geometry.type))], meshOperations: [...new Set(operations)] };+}++/** Grade a recipe: { pass, passed, total, results: [{ kind, label, pass, detail }] }. An invalid recipe fails every check. */+export async function gradeRecipe(task, recipe) {+ let measures;+ try {+ measures = await measureRecipe(recipe);+ } catch (error) {+ const results = task.checks.map(check => ({ kind: check.kind, label: check.label, pass: false, detail: `recipe failed: ${error.message}` }));+ return { pass: false, passed: 0, total: results.length, results };+ }+ const results = task.checks.map(check => ({ kind: check.kind, ...(check.label ? { label: check.label } : {}), ...checkOne(check, measures) }));+ const passed = results.filter(result => result.pass).length;+ return { pass: passed === results.length, passed, total: results.length, results };+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ const [taskId, recipePath] = process.argv.slice(2);+ const grade = await gradeRecipe(taskById(taskId), JSON.parse(await readFile(recipePath, 'utf8')));+ console.log(JSON.stringify(grade, null, 2));+ process.exitCode = grade.pass ? 0 : 1;+}diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjsnew file mode 100644index 00000000..7fce9099--- /dev/null+++ b/bench/agent-modeling/measure.mjs@@ -0,0 +1,250 @@+// Measures the object a recipe builds, in world space, for the agent modeling suite: bounds, parts, closure, holes+// (genus), volume, cross-section loops, lines through the object, gear teeth and UV stretch. Shape measures use every+// node's render triangles in world space. Lint, parts and genus come from the engine's own mesh report, the one the+// agent sees: welding render triangles again can invent non-manifold edges that the polygon mesh does not have.+import { createAgentScene, loadMeshBooleans, needsMeshBooleans } from '../../src/agent-scene.js';++const WELD_DISTANCE = 1e-5;++function transformPoint(matrix, x, y, z) {+ return [+ matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],+ matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],+ matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14],+ ];+}++function worldGeometry(part) {+ const source = part.geometry;+ const positions = new Float32Array(source.positions.length);+ for (let vertex = 0; vertex < source.positions.length / 3; vertex++) {+ const point = transformPoint(part.matrix, source.positions[vertex * 3], source.positions[vertex * 3 + 1], source.positions[vertex * 3 + 2]);+ positions.set(point, vertex * 3);+ }+ // A mirrored matrix flips winding; keep triangles facing out.+ const matrix = part.matrix;+ const determinant = matrix[0] * (matrix[5] * matrix[10] - matrix[6] * matrix[9])+ - matrix[4] * (matrix[1] * matrix[10] - matrix[2] * matrix[9])+ + matrix[8] * (matrix[1] * matrix[6] - matrix[2] * matrix[5]);+ const indices = Uint32Array.from(source.indices);+ if (determinant < 0) {+ for (let triangle = 0; triangle < indices.length; triangle += 3) [indices[triangle + 1], indices[triangle + 2]] = [indices[triangle + 2], indices[triangle + 1]];+ }+ const geometry = { positions, indices };+ if (source.uvs) geometry.uvs = source.uvs;+ return geometry;+}++const triangleArea = (positions, first, second, third) => {+ const ax = positions[second * 3] - positions[first * 3];+ const ay = positions[second * 3 + 1] - positions[first * 3 + 1];+ const az = positions[second * 3 + 2] - positions[first * 3 + 2];+ const bx = positions[third * 3] - positions[first * 3];+ const by = positions[third * 3 + 1] - positions[first * 3 + 1];+ const bz = positions[third * 3 + 2] - positions[first * 3 + 2];+ return Math.hypot(ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx) / 2;+};++function signedVolume({ positions, indices }) {+ let volume = 0;+ for (let triangle = 0; triangle < indices.length; triangle += 3) {+ const [first, second, third] = [indices[triangle], indices[triangle + 1], indices[triangle + 2]];+ const [ax, ay, az] = [positions[first * 3], positions[first * 3 + 1], positions[first * 3 + 2]];+ const [bx, by, bz] = [positions[second * 3], positions[second * 3 + 1], positions[second * 3 + 2]];+ const [cx, cy, cz] = [positions[third * 3], positions[third * 3 + 1], positions[third * 3 + 2]];+ volume += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6;+ }+ return volume;+}++/** Area-weighted mean deviation of the UV-to-surface area ratio from its median; 0 means even texel density. */+function uvStretch({ positions, indices, uvs }) {+ const samples = [];+ for (let triangle = 0; triangle < indices.length; triangle += 3) {+ const [first, second, third] = [indices[triangle], indices[triangle + 1], indices[triangle + 2]];+ const area = triangleArea(positions, first, second, third);+ if (area < 1e-12) continue;+ const uvArea = Math.abs((uvs[second * 2] - uvs[first * 2]) * (uvs[third * 2 + 1] - uvs[first * 2 + 1])+ - (uvs[second * 2 + 1] - uvs[first * 2 + 1]) * (uvs[third * 2] - uvs[first * 2])) / 2;+ samples.push({ ratio: uvArea / area, area });+ }+ if (!samples.length) return 0;+ const sorted = samples.map(sample => sample.ratio).sort((left, right) => left - right);+ const median = sorted[Math.floor(sorted.length / 2)];+ if (median === 0) return Infinity;+ let deviation = 0;+ let totalArea = 0;+ for (const sample of samples) {+ deviation += Math.abs(sample.ratio / median - 1) * sample.area;+ totalArea += sample.area;+ }+ return deviation / totalArea;+}++/** Closed loops where the plane `axis = at` cuts the triangles of all parts. */+export function sectionLoops(geometries, axis, at) {+ const axisIndex = { x: 0, y: 1, z: 2 }[axis];+ const keyOf = point => point.map(value => Math.round(value / WELD_DISTANCE)).join(',');+ const parent = new Map();+ const find = key => {+ while (parent.get(key) !== key) {+ parent.set(key, parent.get(parent.get(key)));+ key = parent.get(key);+ }+ return key;+ };+ const union = (first, second) => {+ for (const key of [first, second]) if (!parent.has(key)) parent.set(key, key);+ parent.set(find(first), find(second));+ };+ for (const { positions, indices } of geometries) {+ for (let triangle = 0; triangle < indices.length; triangle += 3) {+ const corners = [indices[triangle], indices[triangle + 1], indices[triangle + 2]].map(vertex => [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]]);+ const crossings = [];+ for (let side = 0; side < 3; side++) {+ const start = corners[side];+ const end = corners[(side + 1) % 3];+ const startOffset = start[axisIndex] - at;+ const endOffset = end[axisIndex] - at;+ if ((startOffset < 0) === (endOffset < 0)) continue;+ const fraction = startOffset / (startOffset - endOffset);+ crossings.push(start.map((value, component) => value + (end[component] - value) * fraction));+ }+ if (crossings.length === 2) union(keyOf(crossings[0]), keyOf(crossings[1]));+ }+ }+ const roots = new Set();+ for (const key of parent.keys()) roots.add(find(key));+ return roots.size;+}++/**+ * Count separate outer tips around the thinnest axis (gear teeth, star points). Vertices near the outer radius are+ * joined when a triangle edge runs between them along the rim, so a wide flat tooth tip still counts once.+ */+function countTips(geometries, bounds) {+ const extents = [0, 1, 2].map(axis => bounds.max[axis] - bounds.min[axis]);+ const thinAxis = extents.indexOf(Math.min(...extents));+ const [firstAxis, secondAxis] = [0, 1, 2].filter(axis => axis !== thinAxis);+ const center = [0, 1, 2].map(axis => (bounds.max[axis] + bounds.min[axis]) / 2);+ const radiusAt = (first, second) => Math.hypot(first - center[firstAxis], second - center[secondAxis]);+ let outerRadius = 0;+ for (const { positions } of geometries) {+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {+ outerRadius = Math.max(outerRadius, radiusAt(positions[vertex * 3 + firstAxis], positions[vertex * 3 + secondAxis]));+ }+ }+ const tipRadius = outerRadius * 0.97;+ const parent = new Map();+ const find = key => {+ while (parent.get(key) !== key) {+ parent.set(key, parent.get(parent.get(key)));+ key = parent.get(key);+ }+ return key;+ };+ const add = key => {+ if (!parent.has(key)) parent.set(key, key);+ };+ for (const { positions, indices } of geometries) {+ const planeKey = vertex => `${Math.round(positions[vertex * 3 + firstAxis] / WELD_DISTANCE)},${Math.round(positions[vertex * 3 + secondAxis] / WELD_DISTANCE)}`;+ const radiusOf = vertex => radiusAt(positions[vertex * 3 + firstAxis], positions[vertex * 3 + secondAxis]);+ for (let triangle = 0; triangle < indices.length; triangle += 3) {+ for (let side = 0; side < 3; side++) {+ const start = indices[triangle + side];+ const end = indices[triangle + (side + 1) % 3];+ const startIsTip = radiusOf(start) > tipRadius;+ const endIsTip = radiusOf(end) > tipRadius;+ if (startIsTip) add(planeKey(start));+ if (endIsTip) add(planeKey(end));+ if (!startIsTip || !endIsTip) continue;+ const middleFirst = (positions[start * 3 + firstAxis] + positions[end * 3 + firstAxis]) / 2;+ const middleSecond = (positions[start * 3 + secondAxis] + positions[end * 3 + secondAxis]) / 2;+ if (radiusAt(middleFirst, middleSecond) > tipRadius) parent.set(find(planeKey(start)), find(planeKey(end)));+ }+ }+ }+ const roots = new Set();+ for (const key of parent.keys()) roots.add(find(key));+ return roots.size;+}++/** Number of triangles a line along `axis` crosses at the given coordinates of the other two axes, in axis order. */+function lineHits(geometries, axis, point) {+ const axisIndex = { x: 0, y: 1, z: 2 }[axis];+ const [firstAxis, secondAxis] = [0, 1, 2].filter(candidate => candidate !== axisIndex);+ let hits = 0;+ for (const { positions, indices } of geometries) {+ for (let triangle = 0; triangle < indices.length; triangle += 3) {+ const corners = [indices[triangle], indices[triangle + 1], indices[triangle + 2]].map(vertex => [positions[vertex * 3 + firstAxis] - point[0], positions[vertex * 3 + secondAxis] - point[1]]);+ const sides = corners.map((corner, index) => {+ const next = corners[(index + 1) % 3];+ return corner[0] * next[1] - corner[1] * next[0];+ });+ if (sides.every(side => side > 0) || sides.every(side => side < 0)) hits++;+ }+ }+ return hits;+}++/** Load the recipe and measure what it builds. Throws if the recipe itself is invalid. */+export async function measureRecipe(recipe) {+ if (needsMeshBooleans(recipe)) await loadMeshBooleans();+ const scene = createAgentScene(recipe);+ const geometries = scene.parts.map(worldGeometry);+ const reports = new Map();+ const reportOf = id => {+ if (!reports.has(id)) reports.set(id, scene.inspectMeshes({ geometries: [id] }).meshes[0]);+ return reports.get(id);+ };+ const usedGeometries = scene.exportRecipe().nodes.filter(node => node.geometry).map(node => node.geometry);+ const bounds = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] };+ let parts = 0;+ let closedParts = 0;+ let eulerCharacteristic = 0;+ let volume = 0;+ let triangles = 0;+ let lintProblems = 0;+ const problemKinds = new Set();+ let uvParts = 0;+ let worstUvStretch = 0;+ for (const geometry of geometries) {+ for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {+ for (let axis = 0; axis < 3; axis++) {+ bounds.min[axis] = Math.min(bounds.min[axis], geometry.positions[vertex * 3 + axis]);+ bounds.max[axis] = Math.max(bounds.max[axis], geometry.positions[vertex * 3 + axis]);+ }+ }+ volume += signedVolume(geometry);+ triangles += geometry.indices.length / 3;+ if (geometry.uvs) {+ uvParts++;+ worstUvStretch = Math.max(worstUvStretch, uvStretch(geometry));+ }+ }+ for (const id of usedGeometries) {+ const report = reportOf(id);+ parts += report.parts.count;+ closedParts += report.parts.closed;+ eulerCharacteristic += report.counts.vertices - report.counts.edges + report.counts.faces;+ for (const problem of report.problems) problemKinds.add(problem.kind);+ lintProblems += report.problems.length;+ }+ const allClosed = closedParts === parts;+ return {+ nodes: geometries.length,+ parts,+ closedParts,+ holes: allClosed ? (2 * parts - eulerCharacteristic) / 2 : null,+ volume,+ triangles,+ bounds,+ size: [0, 1, 2].map(axis => bounds.max[axis] - bounds.min[axis]),+ lintProblems,+ problemKinds: [...problemKinds],+ uv: { parts: uvParts, of: geometries.length, stretch: worstUvStretch },+ tips: countTips(geometries, bounds),+ section: (axis, at) => sectionLoops(geometries, axis, at),+ lineHits: (axis, point) => lineHits(geometries, axis, point),+ };+}diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjsnew file mode 100644index 00000000..bd9e6138--- /dev/null+++ b/bench/agent-modeling/references.mjs@@ -0,0 +1,142 @@+// One hand-built solution per task. tests/agent-modeling-suite.test.js grades them, so a checker that rejects a+// correct object, or a task whose numbers do not add up, fails before any agent run is spent on it.++const material = [{ id: 'paint', color: [0.6, 0.55, 0.5] }];++function scene(geometries, nodes) {+ return { format: '67js.scene', schemaVersion: 1, geometries, materials: material, nodes: nodes.map(node => ({ material: 'paint', ...node })) };+}++function axisRotation(axis, angle) {+ const half = angle / 2;+ const quaternion = [0, 0, 0, Math.cos(half)];+ quaternion['xyz'.indexOf(axis)] = Math.sin(half);+ return quaternion;+}++function circle(radius, points, centerX = 0, centerY = 0, clockwise = false) {+ return Array.from({ length: points }, (_, index) => {+ const angle = (clockwise ? -1 : 1) * index / points * Math.PI * 2;+ return [centerX + radius * Math.cos(angle), centerY + radius * Math.sin(angle)];+ });+}++function rectangle(minimumX, minimumY, maximumX, maximumY, clockwise = false) {+ const ring = [[minimumX, minimumY], [maximumX, minimumY], [maximumX, maximumY], [minimumX, maximumY]];+ return clockwise ? ring.reverse() : ring;+}++const crateEdits = [+ { op: 'translate', select: { tag: 'right' }, offset: [-0.2, 0, 0] },+ { op: 'translate', select: { tag: 'left' }, offset: [0.2, 0, 0] },+ { op: 'translate', select: { tag: 'front' }, offset: [0, 0, -0.2] },+ { op: 'translate', select: { tag: 'back' }, offset: [0, 0, 0.2] },+ { op: 'translate', select: { tag: 'top' }, offset: [0, -0.2, 0] },+ { op: 'translate', select: { tag: 'bottom' }, offset: [0, 0.2, 0] },+ { op: 'inset_individual', select: { tag: 'side' }, thickness: 0.04, name: 'panel' },+ { op: 'extrude_individual', select: { tag: 'panel.cap' }, offset: -0.02 },+ { op: 'inset_region', select: { tag: 'top' }, thickness: 0.05, name: 'lid' },+ { op: 'extrude_face_region', select: { tag: 'lid.cap' }, offset: 0.03 },+];++function hexagon(acrossFlats) {+ const radius = acrossFlats / Math.sqrt(3);+ return circle(radius, 6);+}++function gearContour(teeth, tipRadius, rootRadius) {+ const points = [];+ for (let tooth = 0; tooth < teeth; tooth++) {+ const base = tooth / teeth * Math.PI * 2;+ const step = Math.PI * 2 / teeth;+ for (const [fraction, radius] of [[0, rootRadius], [0.15, rootRadius], [0.3, tipRadius], [0.55, tipRadius], [0.7, rootRadius]]) {+ const angle = base + fraction * step;+ points.push([radius * Math.cos(angle), radius * Math.sin(angle)]);+ }+ }+ return points;+}++export const REFERENCES = {+ crate: scene(+ [{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: crateEdits }],+ [{ id: 'crate', geometry: 'crate', translation: [0, 0.3, 0] }],+ ),+ 'crate-uv': scene(+ [{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [...crateEdits, { op: 'uv_unwrap' }] }],+ [{ id: 'crate', geometry: 'crate', translation: [0, 0.3, 0] }],+ ),+ bolt: scene(+ [+ { id: 'shaft', type: 'cylinder', segments: 32, bevel: 0 },+ { id: 'head', type: 'extrude', contour: hexagon(0.05), depth: 0.02 },+ ],+ [+ { id: 'shaft', geometry: 'shaft', translation: [0, 0.06, 0], scale: [0.015, 0.12, 0.015] },+ { id: 'head', geometry: 'head', translation: [0, 0.12, 0], rotation: axisRotation('x', -Math.PI / 2) },+ ],+ ),+ // An extrude with these four holes leaves T-junctions in its caps (collinear hole edges), so this cuts the panes.+ window: scene(+ [{+ id: 'frame', type: 'mesh', base: { type: 'box', bevel: 0 },+ edits: [[-0.235, 0.315], [0.235, 0.315], [-0.235, 0.885], [0.235, 0.885]].map(([x, y], index) => ({+ op: 'boolean', operation: 'difference', name: `pane-${index}`, cutter: { type: 'box', bevel: 0 },+ translation: [x, (y - 0.6) / 1.2, 0], scale: [0.41, 0.51 / 1.2, 2],+ })),+ }],+ [{ id: 'frame', geometry: 'frame', translation: [0, 0.6, 0], scale: [1, 1.2, 0.08] }],+ ),+ table: scene(+ [{ id: 'block', type: 'box', bevel: 0 }],+ [+ { id: 'top', geometry: 'block', translation: [0, 0.73, 0], scale: [1.2, 0.04, 0.75] },+ ...[[-1, -1], [-1, 1], [1, -1], [1, 1]].map(([signX, signZ], index) => ({+ id: `leg-${index}`, geometry: 'block', translation: [signX * 0.525, 0.355, signZ * 0.2], scale: [0.05, 0.71, 0.05],+ })),+ ],+ ),+ mug: scene(+ [{+ id: 'mug', type: 'mesh', base: { type: 'cylinder', segments: 48, bevel: 0 }, edits: [+ { op: 'boolean', operation: 'union', name: 'handle', cutter: { type: 'torus', tubeRadius: 0.25, segments: 48, sides: 12 }, translation: [1.19, 0, 0], scale: [0.45, 0.28, 0.45] },+ { op: 'boolean', operation: 'difference', name: 'cavity', cutter: { type: 'cylinder', segments: 48, bevel: 0 }, translation: [0, 0.05, 0], scale: [0.875, 1, 0.875] },+ ],+ }],+ [{ id: 'mug', geometry: 'mug', translation: [0, 0.05, 0], scale: [0.04, 0.1, 0.04] }],+ ),+ gear: scene(+ [{ id: 'gear', type: 'extrude', contour: gearContour(12, 0.1, 0.085), holes: [circle(0.02, 32, 0, 0, true)], depth: 0.02 }],+ [{ id: 'gear', geometry: 'gear', rotation: axisRotation('x', -Math.PI / 2) }],+ ),+ fence: scene(+ [{ id: 'block', type: 'box', bevel: 0 }],+ [+ ...[-1, -0.5, 0, 0.5, 1].map((x, index) => ({ id: `post-${index}`, geometry: 'block', translation: [x, 0.5, 0], scale: [0.08, 1, 0.08] })),+ { id: 'rail-low', geometry: 'block', translation: [0, 0.3, 0], scale: [2.08, 0.04, 0.06] },+ { id: 'rail-high', geometry: 'block', translation: [0, 0.8, 0], scale: [2.08, 0.04, 0.06] },+ ],+ ),+ bracket: scene(+ [+ { id: 'base', type: 'extrude', depth: 0.02, contour: rectangle(-0.1, -0.05, 0.1, 0.05), holes: [circle(0.01, 32, 0, 0, true), circle(0.01, 32, 0.06, 0, true)] },+ { id: 'block', type: 'box', bevel: 0 },+ ],+ [+ { id: 'base', geometry: 'base', rotation: axisRotation('x', -Math.PI / 2) },+ { id: 'upright', geometry: 'block', translation: [-0.09, 0.095, 0], scale: [0.02, 0.15, 0.1] },+ ],+ ),+ soap: scene(+ [{ id: 'soap', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [+ { op: 'translate', select: { tag: 'right' }, offset: [-0.455, 0, 0] },+ { op: 'translate', select: { tag: 'left' }, offset: [0.455, 0, 0] },+ { op: 'translate', select: { tag: 'top' }, offset: [0, -0.485, 0] },+ { op: 'translate', select: { tag: 'bottom' }, offset: [0, 0.485, 0] },+ { op: 'translate', select: { tag: 'front' }, offset: [0, 0, -0.47] },+ { op: 'translate', select: { tag: 'back' }, offset: [0, 0, 0.47] },+ { op: 'bevel', edges: { all: true }, width: 0.01, segments: 4 },+ ] }],+ [{ id: 'soap', geometry: 'soap', translation: [0, 0.015, 0] }],+ ),+};diff --git a/bench/agent-modeling/regrade.mjs b/bench/agent-modeling/regrade.mjsnew file mode 100644index 00000000..bb02369e--- /dev/null+++ b/bench/agent-modeling/regrade.mjs@@ -0,0 +1,29 @@+// Grades a finished run's saved recipes again after a checker fix, without spending another agent run.+// node bench/agent-modeling/regrade.mjs <run name>+import { readFile, writeFile } from 'node:fs/promises';+import { join, resolve } from 'node:path';+import { gradeRecipe, recipeFeatures } from './check.mjs';+import { taskById } from './tasks.mjs';++const repository = resolve(import.meta.dirname, '../..');+const [runName] = process.argv.slice(2);+const summaryPath = join(repository, 'bench', 'agent-modeling', 'results', `${runName}.json`);+const summary = JSON.parse(await readFile(summaryPath, 'utf8'));+for (const record of summary.records) {+ let recipe;+ try {+ recipe = JSON.parse(await readFile(join(repository, 'artifacts', 'agent-modeling', runName, `${record.task}.recipe.json`), 'utf8'));+ } catch {+ continue;+ }+ const grade = await gradeRecipe(taskById(record.task), recipe);+ record.features = recipeFeatures(recipe);+ record.pass = grade.pass;+ record.passed = grade.passed;+ record.total = grade.total;+ record.failed = grade.results.filter(result => !result.pass).map(result => `${result.label ?? result.kind}: ${result.detail}`);+ console.log(`${record.task.padEnd(9)} ${record.pass ? 'PASS' : 'FAIL'} ${record.passed}/${record.total}${record.failed.length ? ` ${record.failed.join(' | ')}` : ''}`);+}+summary.passed = summary.records.filter(record => record.pass).length;+await writeFile(summaryPath, `${JSON.stringify(summary, null, 2)}\n`);+console.log(`${summary.passed}/${summary.tasks} passed.`);diff --git a/bench/agent-modeling/results/2026-10-30-07-48-sonnet-baseline.json b/bench/agent-modeling/results/2026-10-30-07-48-sonnet-baseline.jsonnew file mode 100644index 00000000..25e9fd0d--- /dev/null+++ b/bench/agent-modeling/results/2026-10-30-07-48-sonnet-baseline.json@@ -0,0 +1,336 @@+{+ "run": "2026-10-30-07-48-sonnet-baseline",+ "model": "claude-sonnet-5-5",+ "date": "2026-10-30T07:56:00.910Z",+ "passed": 10,+ "tasks": 10,+ "toolCalls": 67,+ "costUsd": 4.76,+ "records": [+ {+ "task": "crate",+ "pass": true,+ "passed": 8,+ "total": 8,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 5,+ "toolErrors": 0,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_capabilities": 1,+ "scene_create": 1,+ "scene_look": 1,+ "scene_inspect": 1,+ "scene_export_recipe": 1+ },+ "turns": 7,+ "costUsd": 0.4308914000000001,+ "inputTokens": 467371,+ "outputTokens": 2094,+ "wallSeconds": 37,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "mesh",+ "box"+ ],+ "meshOperations": [+ "boolean"+ ]+ }+ },+ {+ "task": "bolt",+ "pass": true,+ "passed": 7,+ "total": 7,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 3,+ "toolErrors": 0,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_create": 1,+ "scene_look": 1,+ "scene_export_recipe": 1+ },+ "turns": 5,+ "costUsd": 0.4098161,+ "inputTokens": 456575,+ "outputTokens": 1406,+ "wallSeconds": 33,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "lathe"+ ],+ "meshOperations": []+ }+ },+ {+ "task": "window",+ "pass": true,+ "passed": 5,+ "total": 5,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 10,+ "toolErrors": 1,+ "toolsByName": {+ "ToolSearch": 2,+ "scene_create": 1,+ "scene_inspect": 1,+ "mesh_inspect": 4,+ "scene_apply": 2,+ "scene_look": 1,+ "scene_export_recipe": 1+ },+ "turns": 13,+ "costUsd": 0.5218303999999999,+ "inputTokens": 1125060,+ "outputTokens": 3631,+ "wallSeconds": 51,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "box"+ ],+ "meshOperations": []+ }+ },+ {+ "task": "table",+ "pass": true,+ "passed": 6,+ "total": 6,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 4,+ "toolErrors": 1,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_create": 1,+ "scene_inspect": 1,+ "scene_look": 1,+ "scene_export_recipe": 1+ },+ "turns": 6,+ "costUsd": 0.4144607,+ "inputTokens": 458461,+ "outputTokens": 1524,+ "wallSeconds": 36,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "box"+ ],+ "meshOperations": []+ }+ },+ {+ "task": "mug",+ "pass": true,+ "passed": 7,+ "total": 7,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 5,+ "toolErrors": 1,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_create": 2,+ "scene_look": 1,+ "scene_inspect": 1,+ "scene_export_recipe": 1+ },+ "turns": 7,+ "costUsd": 0.45834559999999996,+ "inputTokens": 576539,+ "outputTokens": 3543,+ "wallSeconds": 45,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "mesh"+ ],+ "meshOperations": [+ "boolean"+ ]+ }+ },+ {+ "task": "gear",+ "pass": true,+ "passed": 5,+ "total": 5,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 7,+ "toolErrors": 2,+ "toolsByName": {+ "ToolSearch": 2,+ "Bash": 1,+ "scene_create": 1,+ "scene_look": 1,+ "scene_inspect": 1,+ "mesh_inspect": 2,+ "scene_export_recipe": 1+ },+ "turns": 10,+ "costUsd": 0.5339972,+ "inputTokens": 922371,+ "outputTokens": 6389,+ "wallSeconds": 74,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "extrude"+ ],+ "meshOperations": []+ }+ },+ {+ "task": "fence",+ "pass": true,+ "passed": 6,+ "total": 6,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 7,+ "toolErrors": 1,+ "toolsByName": {+ "ToolSearch": 2,+ "scene_create": 2,+ "scene_capabilities": 1,+ "scene_look": 1,+ "scene_dispose": 2,+ "scene_export_recipe": 1+ },+ "turns": 10,+ "costUsd": 0.4854696,+ "inputTokens": 909941,+ "outputTokens": 2602,+ "wallSeconds": 47,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "box"+ ],+ "meshOperations": []+ }+ },+ {+ "task": "bracket",+ "pass": true,+ "passed": 6,+ "total": 6,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 5,+ "toolErrors": 0,+ "toolsByName": {+ "ToolSearch": 2,+ "scene_create": 1,+ "scene_capabilities": 1,+ "mesh_inspect": 1,+ "mesh_edit": 1,+ "scene_export_recipe": 1+ },+ "turns": 8,+ "costUsd": 0.4531632,+ "inputTokens": 684601,+ "outputTokens": 2145,+ "wallSeconds": 36,+ "exitCode": 0,+ "stopped": "success",+ "note": "Rerun after the prompt stated the total height.",+ "features": {+ "geometryTypes": [+ "mesh"+ ],+ "meshOperations": [+ "boolean"+ ]+ }+ },+ {+ "task": "soap",+ "pass": true,+ "passed": 7,+ "total": 7,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 11,+ "toolErrors": 2,+ "toolsByName": {+ "ToolSearch": 2,+ "scene_create": 3,+ "mesh_inspect": 3,+ "scene_dispose": 2,+ "scene_look": 1,+ "scene_inspect": 1,+ "scene_export_recipe": 1+ },+ "turns": 14,+ "costUsd": 0.5465183,+ "inputTokens": 1351684,+ "outputTokens": 3731,+ "wallSeconds": 63,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "mesh"+ ],+ "meshOperations": [+ "bevel"+ ]+ }+ },+ {+ "task": "crate-uv",+ "pass": true,+ "passed": 9,+ "total": 9,+ "failed": [],+ "model": "claude-sonnet-5-5",+ "toolCalls": 10,+ "toolErrors": 0,+ "toolsByName": {+ "ToolSearch": 1,+ "scene_create": 1,+ "scene_capabilities": 1,+ "mesh_inspect": 3,+ "scene_look": 2,+ "mesh_edit": 1,+ "scene_apply": 1,+ "scene_export_recipe": 1+ },+ "turns": 12,+ "costUsd": 0.5007357,+ "inputTokens": 817239,+ "outputTokens": 3473,+ "wallSeconds": 43,+ "exitCode": 0,+ "stopped": "success",+ "features": {+ "geometryTypes": [+ "mesh"+ ],+ "meshOperations": [+ "inset_region",+ "extrude_face_region",+ "uv_unwrap"+ ]+ }+ }+ ]+}diff --git a/bench/agent-modeling/run.mjs b/bench/agent-modeling/run.mjsnew file mode 100644index 00000000..434f9b07--- /dev/null+++ b/bench/agent-modeling/run.mjs@@ -0,0 +1,182 @@+// Runs the agent modeling suite: one fresh, non-interactive Claude Code session per task, with only the 67.js MCP+// server, then grades the recipe the agent exported.+//+// node bench/agent-modeling/run.mjs --claude <claude executable> [--model sonnet] [--tasks crate,bolt]+// [--budget 3] [--timeout 1200] [--label baseline]+//+// Raw transcripts and recipes go to artifacts/agent-modeling/<run>/ (ignored by Git); the summary goes to+// bench/agent-modeling/results/<run>.json.+import { spawn } from 'node:child_process';+import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { parseArgs } from 'node:util';+import { gradeRecipe, recipeFeatures } from './check.mjs';+import { PROMPT_PREAMBLE, TASKS, taskById } from './tasks.mjs';++const repository = resolve(import.meta.dirname, '../..');+const MCP_SERVER_NAME = '67js';+const EXPORT_TOOL = `mcp__${MCP_SERVER_NAME}__scene_export_recipe`;+const BUILT_IN_TOOLS = ['Bash', 'PowerShell', 'Read', 'Edit', 'Write', 'Glob', 'Grep', 'WebFetch', 'WebSearch', 'Agent', 'Task', 'NotebookEdit'];++const { values: options } = parseArgs({+ options: {+ claude: { type: 'string', default: process.env.CLAUDE_EXECUTABLE ?? 'claude' },+ model: { type: 'string', default: 'sonnet' },+ tasks: { type: 'string' },+ budget: { type: 'string', default: '3' },+ timeout: { type: 'string', default: '1200' },+ label: { type: 'string', default: 'run' },+ },+});++const runName = `${new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-')}-${options.model}-${options.label}`;+const rawDirectory = join(repository, 'artifacts', 'agent-modeling', runName);+const resultsDirectory = join(repository, 'bench', 'agent-modeling', 'results');++function mcpConfig() {+ return { mcpServers: { [MCP_SERVER_NAME]: {+ command: process.execPath,+ args: [join(repository, 'scripts', 'mcp-server.mjs'), '--backend', 'gpu', '--memory', '192'],+ } } };+}++function runClaude(prompt, workingDirectory, configPath) {+ const argumentsList = [+ '-p', prompt,+ '--model', options.model,+ '--output-format', 'stream-json', '--verbose',+ '--mcp-config', configPath, '--strict-mcp-config',+ '--allowedTools', `mcp__${MCP_SERVER_NAME}`,+ '--disallowedTools', ...BUILT_IN_TOOLS,+ '--permission-mode', 'dontAsk',+ '--setting-sources', 'project',+ '--no-session-persistence',+ '--max-budget-usd', options.budget,+ ];+ return new Promise(resolvePromise => {+ const started = performance.now();+ const child = spawn(options.claude, argumentsList, { cwd: workingDirectory, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });+ let output = '';+ let errors = '';+ child.stdout.on('data', chunk => {+ output += chunk;+ });+ child.stderr.on('data', chunk => {+ errors += chunk;+ });+ const timer = setTimeout(() => child.kill(), Number(options.timeout) * 1000);+ child.on('close', code => {+ clearTimeout(timer);+ resolvePromise({ output, errors, code, wallMs: Math.round(performance.now() - started) });+ });+ });+}++function textOf(content) {+ if (typeof content === 'string') return content;+ return (content ?? []).filter(block => block.type === 'text').map(block => block.text).join('');+}++/** Tool calls, errors, the model, usage and the last exported recipe from a stream-json transcript. */+function readTranscript(output) {+ const summary = { model: null, toolCalls: 0, toolErrors: 0, toolsByName: {}, recipe: null, result: null };+ const exportCalls = new Set();+ for (const line of output.split('\n')) {+ if (!line.trim().startsWith('{')) continue;+ let event;+ try {+ event = JSON.parse(line);+ } catch {+ continue;+ }+ if (event.type === 'system' && event.subtype === 'init') summary.model = event.model;+ if (event.type === 'assistant') {+ for (const block of event.message?.content ?? []) {+ if (block.type !== 'tool_use') continue;+ const name = block.name.replace(`mcp__${MCP_SERVER_NAME}__`, '');+ // ToolSearch only loads the MCP tool schemas; it is harness overhead, not modeling work.+ if (block.name !== 'ToolSearch') summary.toolCalls++;+ summary.toolsByName[name] = (summary.toolsByName[name] ?? 0) + 1;+ if (block.name === EXPORT_TOOL) exportCalls.add(block.id);+ }+ }+ if (event.type === 'user') {+ for (const block of event.message?.content ?? []) {+ if (block.type !== 'tool_result') continue;+ if (block.is_error) summary.toolErrors++;+ if (!exportCalls.has(block.tool_use_id) || block.is_error) continue;+ try {+ const exported = JSON.parse(textOf(block.content));+ summary.recipe = exported.format ? exported : exported.recipe ?? null;+ } catch {+ // Not JSON: the export failed; the task is graded as having no recipe.+ }+ }+ }+ if (event.type === 'result') summary.result = event;+ }+ return summary;+}++async function runTask(task) {+ const workingDirectory = await mkdtemp(join(tmpdir(), '67js-agent-task-'));+ try {+ const configPath = join(workingDirectory, 'mcp.json');+ await writeFile(configPath, JSON.stringify(mcpConfig()));+ const prompt = `${PROMPT_PREAMBLE}\n\n${task.prompt.replace(/\n/g, ' ')}`;+ const run = await runClaude(prompt, workingDirectory, configPath);+ const transcript = readTranscript(run.output);+ await writeFile(join(rawDirectory, `${task.id}.jsonl`), run.output);+ if (run.errors) await writeFile(join(rawDirectory, `${task.id}.stderr.txt`), run.errors);+ if (transcript.recipe) await writeFile(join(rawDirectory, `${task.id}.recipe.json`), JSON.stringify(transcript.recipe, null, 2));+ const grade = transcript.recipe+ ? await gradeRecipe(task, transcript.recipe)+ : { pass: false, passed: 0, total: task.checks.length, results: [{ kind: 'export', pass: false, detail: 'no exported recipe' }] };+ const usage = transcript.result?.usage ?? {};+ return {+ task: task.id,+ pass: grade.pass,+ passed: grade.passed,+ total: grade.total,+ failed: grade.results.filter(result => !result.pass).map(result => `${result.label ?? result.kind}: ${result.detail}`),+ model: transcript.model,+ toolCalls: transcript.toolCalls,+ toolErrors: transcript.toolErrors,+ toolsByName: transcript.toolsByName,+ features: transcript.recipe ? recipeFeatures(transcript.recipe) : null,+ turns: transcript.result?.num_turns ?? null,+ costUsd: transcript.result?.total_cost_usd ?? null,+ inputTokens: (usage.input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) + (usage.cache_creation_input_tokens ?? 0),+ outputTokens: usage.output_tokens ?? 0,+ wallSeconds: Math.round(run.wallMs / 1000),+ exitCode: run.code,+ stopped: transcript.result?.subtype ?? 'no result',+ };+ } finally {+ await rm(workingDirectory, { recursive: true, force: true });+ }+}++const tasks = options.tasks ? options.tasks.split(',').map(taskById) : TASKS;+await mkdir(rawDirectory, { recursive: true });+await mkdir(resultsDirectory, { recursive: true });+const records = [];+for (const task of tasks) {+ const record = await runTask(task);+ records.push(record);+ console.log(`${record.task.padEnd(9)} ${record.pass ? 'PASS' : 'FAIL'} ${record.passed}/${record.total} calls ${record.toolCalls} (errors ${record.toolErrors}) $${record.costUsd ?? '?'} ${record.wallSeconds}s${record.failed.length ? ` ${record.failed.join(' | ')}` : ''}`);+}+const summary = {+ run: runName,+ model: records.find(record => record.model)?.model ?? options.model,+ claudeCode: options.claude,+ date: new Date().toISOString(),+ passed: records.filter(record => record.pass).length,+ tasks: records.length,+ toolCalls: records.reduce((sum, record) => sum + record.toolCalls, 0),+ costUsd: Number(records.reduce((sum, record) => sum + (record.costUsd ?? 0), 0).toFixed(2)),+ records,+};+await writeFile(join(resultsDirectory, `${runName}.json`), `${JSON.stringify(summary, null, 2)}\n`);+console.log(`${summary.passed}/${summary.tasks} passed, ${summary.toolCalls} tool calls, $${summary.costUsd}. Summary: bench/agent-modeling/results/${runName}.json`);diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjsnew file mode 100644index 00000000..73614d77--- /dev/null+++ b/bench/agent-modeling/tasks.mjs@@ -0,0 +1,159 @@+// The agent modeling tasks. Each prompt gives sizes in metres, so every check is objective. Checks run on the recipe+// the agent exports (see measure.mjs and check.mjs); none of them looks at how the object was built.++export const PROMPT_PREAMBLE = `You are modeling with the 67.js MCP tools. Build the object described below as a procedural recipe scene:+start it with scene_create, refine it with mesh_edit, mesh_stack and scene_apply, and look at it with scene_look when+that helps. Units are metres and Y is up. Rest the object on the ground (lowest point at Y = 0), centred on X = 0 and+Z = 0. Build it as closed, watertight solids. When the object is finished, call scene_export_recipe once: the exported+recipe is what gets graded.`;++const crateChecks = [+ { kind: 'lint' },+ { kind: 'size', expected: [0.6, 0.63, 0.6] },+ { kind: 'ground' },+ { kind: 'holes', equals: 0 },+ { kind: 'volume', min: 0.19, max: 0.212 },+ { kind: 'section', axis: 'x', at: 0.29, equals: 2, label: 'recessed panel on +X' },+ { kind: 'section', axis: 'z', at: -0.29, equals: 2, label: 'recessed panel on -Z' },+ { kind: 'section', axis: 'y', at: 0.615, equals: 1, label: 'raised lid' },+];++export const TASKS = [+ {+ id: 'crate',+ prompt: `A wooden crate. The body is a 0.6 m cube. Each of its four sides has a recessed panel: a frame about+0.04 m wide around a panel sunk about 0.02 m into the side. On top sits a raised lid, inset about 0.05 m from the top+edges and 0.03 m tall.`,+ checks: crateChecks,+ },+ {+ id: 'bolt',+ prompt: `A hex bolt standing upright with the shaft pointing down. The shaft is a cylinder 0.03 m in diameter and+0.12 m long, its tip on the ground. The head on top is a regular hexagonal prism 0.05 m across the flats and 0.02 m+tall.`,+ checks: [+ { kind: 'lint' },+ { kind: 'size', expected: [null, 0.14, null] },+ { kind: 'extent', axes: ['x', 'z'], min: 0.05, max: 0.058 },+ { kind: 'ground' },+ { kind: 'holes', equals: 0 },+ { kind: 'volume', min: 1.13e-4, max: 1.43e-4 },+ { kind: 'section', axis: 'y', at: 0.06, equals: 1, label: 'one shaft' },+ ],+ },+ {+ id: 'window',+ prompt: `A window frame standing upright in the XY plane: 1.0 m wide (X), 1.2 m tall (Y) and 0.08 m deep (Z). The+outer frame and the cross bars are all 0.06 m wide, dividing it into four open panes of equal size, two by two. No+glass: the panes are open.`,+ checks: [+ { kind: 'lint' },+ { kind: 'size', expected: [1.0, 1.2, 0.08] },+ { kind: 'ground' },+ {+ kind: 'through', axis: 'z', label: 'four open panes',+ open: [[-0.235, 0.315], [0.235, 0.315], [-0.235, 0.885], [0.235, 0.885]],+ solid: [[-0.47, 0.6], [0.47, 0.6], [0.013, 0.3], [0.013, 0.9], [-0.2, 0.6], [0.2, 0.6], [-0.2, 0.03], [0.2, 1.17]],+ },+ { kind: 'volume', min: 0.0256, max: 0.0326 },+ ],+ },+ {+ id: 'table',+ prompt: `A table. The top is 1.2 m long (X), 0.75 m deep (Z) and 0.04 m thick, with its upper surface 0.75 m above+the ground. Four square legs, 0.05 m on a side, run from the ground to the underside of the top; each leg's outer faces+sit 0.05 m in from the edges of the top.`,+ checks: [+ { kind: 'lint' },+ { kind: 'size', expected: [1.2, 0.75, 0.75] },+ { kind: 'ground' },+ { kind: 'section', axis: 'y', at: 0.02, equals: 4, label: 'four legs at the floor' },+ { kind: 'section', axis: 'y', at: 0.7, equals: 4, label: 'four legs under the top' },+ { kind: 'volume', min: 0.0388, max: 0.0474 },+ ],+ },+ {+ id: 'mug',+ prompt: `A mug made as one solid piece. The cup is a cylinder 0.08 m in diameter and 0.1 m tall, open at the top,+with 0.005 m thick walls and a 0.005 m thick bottom. A loop handle on the +X side joins the outer wall at two points,+leaving a gap for fingers, and reaches about 0.03 m out from the wall.`,+ checks: [+ { kind: 'lint' },+ { kind: 'parts', max: 1 },+ { kind: 'size', expected: [null, 0.1, 0.08] },+ { kind: 'extent', axes: ['x'], min: 0.1, max: 0.13 },+ { kind: 'ground', centred: false },+ { kind: 'holes', equals: 1 },+ { kind: 'volume', min: 1.1e-4, max: 2.4e-4 },+ ],+ },+ {+ id: 'gear',+ prompt: `A spur gear lying flat on the ground: 12 teeth, outer (tip) radius 0.1 m, root radius 0.085 m, 0.02 m+thick, with a round centre bore of radius 0.02 m going all the way through.`,+ checks: [+ { kind: 'lint' },+ { kind: 'size', expected: [0.2, 0.02, 0.2] },+ { kind: 'ground' },+ { kind: 'holes', equals: 1 },+ { kind: 'tips', equals: 12 },+ ],+ },+ {+ id: 'fence',+ prompt: `A fence section. Five square posts, 0.08 m on a side and 1.0 m tall, stand in a row along X with their+centres 0.5 m apart. Two horizontal rails, 0.04 m tall and 0.06 m deep, run the full length from the outer face of the+first post to the outer face of the last, centred at heights 0.3 m and 0.8 m and centred on the posts in Z.`,+ checks: [+ { kind: 'lint' },+ { kind: 'size', expected: [2.08, 1.0, 0.08] },+ { kind: 'ground' },+ { kind: 'section', axis: 'y', at: 0.1, equals: 5, label: 'five posts' },+ { kind: 'section', axis: 'x', at: 0.25, equals: 2, label: 'two rails between posts' },+ { kind: 'volume', min: 0.037, max: 0.047 },+ ],+ },+ {+ id: 'bracket',+ prompt: `An L bracket. The base plate is 0.2 m long (X), 0.02 m thick (Y) and 0.1 m deep (Z), lying on the ground.+An upright plate 0.02 m thick (X) and 0.1 m deep stands on top of the base, flush with its -X end, and rises 0.15 m+above it, so the bracket is 0.17 m tall overall. Two round+holes, 0.02 m in diameter, go straight down through the base at X = 0 and X = 0.06 (centred in Z).`,+ checks: [+ { kind: 'lint' },+ { kind: 'size', expected: [0.2, 0.17, 0.1] },+ { kind: 'ground' },+ { kind: 'holes', equals: 2 },+ { kind: 'volume', min: 6.2e-4, max: 7.6e-4 },+ { kind: 'section', axis: 'y', at: 0.01, equals: 3, label: 'base with two holes' },+ ],+ },+ {+ id: 'soap',+ prompt: `A bar of soap: 0.09 m long (X), 0.03 m tall (Y) and 0.06 m deep (Z), with every edge and corner smoothly+rounded to a radius of about 0.01 m.`,+ checks: [+ { kind: 'lint' },+ { kind: 'parts', max: 1 },+ { kind: 'size', expected: [0.09, 0.03, 0.06] },+ { kind: 'ground' },+ { kind: 'holes', equals: 0 },+ { kind: 'volume', min: 1.3e-4, max: 1.56e-4 },+ { kind: 'triangles', min: 200 },+ ],+ },+ {+ id: 'crate-uv',+ prompt: `A wooden crate that will get a tiled wood texture. The body is a 0.6 m cube. Each of its four sides has a+recessed panel: a frame about 0.04 m wide around a panel sunk about 0.02 m into the side. On top sits a raised lid,+inset about 0.05 m from the top edges and 0.03 m tall. Give every part UV coordinates with even texel density and no+stretching.`,+ checks: [...crateChecks, { kind: 'uv', maxStretch: 0.15 }],+ },+];++export function taskById(id) {+ const task = TASKS.find(candidate => candidate.id === id);+ if (!task) throw new RangeError(`Unknown task ${id}. Tasks: ${TASKS.map(candidate => candidate.id).join(', ')}.`);+ return task;+}diff --git a/tests/agent-modeling-suite.test.js b/tests/agent-modeling-suite.test.jsnew file mode 100644index 00000000..38d2a358--- /dev/null+++ b/tests/agent-modeling-suite.test.js@@ -0,0 +1,43 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { gradeRecipe } from '../bench/agent-modeling/check.mjs';+import { TASKS, taskById } from '../bench/agent-modeling/tasks.mjs';+import { REFERENCES } from '../bench/agent-modeling/references.mjs';++const failedKinds = grade => grade.results.filter(result => !result.pass).map(result => result.label ?? result.kind);++test('every task has a reference solution that passes all its checks', async () => {+ assert.deepEqual(Object.keys(REFERENCES).sort(), TASKS.map(task => task.id).sort());+ for (const task of TASKS) {+ const grade = await gradeRecipe(task, REFERENCES[task.id]);+ assert.equal(grade.pass, true, `${task.id}: ${JSON.stringify(grade.results.filter(result => !result.pass))}`);+ }+});++test('checks reject objects that miss the asked-for features', async () => {+ const plainCrate = structuredClone(REFERENCES.crate);+ plainCrate.geometries[0].edits = plainCrate.geometries[0].edits.slice(0, 6);+ assert.deepEqual(failedKinds(await gradeRecipe(taskById('crate'), plainCrate)).sort(),+ ['raised lid', 'recessed panel on +X', 'recessed panel on -Z', 'size', 'volume'].sort());++ const noUv = await gradeRecipe(taskById('crate-uv'), REFERENCES.crate);+ assert.deepEqual(failedKinds(noUv), ['uv']);++ const solidWindow = structuredClone(REFERENCES.window);+ solidWindow.geometries[0].edits = solidWindow.geometries[0].edits.slice(0, 2);+ assert.ok(failedKinds(await gradeRecipe(taskById('window'), solidWindow)).includes('four open panes'));++ const floatingTable = structuredClone(REFERENCES.table);+ floatingTable.nodes = floatingTable.nodes.map(node => ({ ...node, translation: [node.translation[0], node.translation[1] + 0.1, node.translation[2]] }));+ assert.ok(failedKinds(await gradeRecipe(taskById('table'), floatingTable)).includes('ground'));++ const elevenTeeth = structuredClone(REFERENCES.gear);+ elevenTeeth.geometries[0].contour = elevenTeeth.geometries[0].contour.slice(0, 55);+ assert.ok(failedKinds(await gradeRecipe(taskById('gear'), elevenTeeth)).includes('tips'));+});++test('an invalid recipe fails every check with the reason', async () => {+ const grade = await gradeRecipe(taskById('bolt'), { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [{ id: 'x', geometry: 'missing' }] });+ assert.equal(grade.passed, 0);+ assert.match(grade.results[0].detail, /recipe failed/);+});