@tangle-network/agent-bench 0.14.4 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +2 -3
  3. package/dist/adapters.d.ts +2 -5
  4. package/dist/adapters.js +3 -4
  5. package/dist/benchmarks/_harness.d.ts +17 -20
  6. package/dist/benchmarks/_harness.js +4 -4
  7. package/dist/benchmarks/_harness.js.map +1 -1
  8. package/dist/benchmarks/aec-bench.d.ts +1 -4
  9. package/dist/benchmarks/aec-bench.js +1 -2
  10. package/dist/benchmarks/agentbench.d.ts +2 -5
  11. package/dist/benchmarks/agentbench.js +1 -2
  12. package/dist/benchmarks/appworld.d.ts +8 -10
  13. package/dist/benchmarks/appworld.js +23 -23
  14. package/dist/benchmarks/appworld.js.map +1 -1
  15. package/dist/benchmarks/bfcl.d.ts +2 -5
  16. package/dist/benchmarks/bfcl.js +1 -2
  17. package/dist/benchmarks/cad-design.d.ts +2 -5
  18. package/dist/benchmarks/cad-design.js +2 -3
  19. package/dist/benchmarks/cad-design.js.map +1 -1
  20. package/dist/benchmarks/cadbench.d.ts +1 -4
  21. package/dist/benchmarks/cadbench.js +1 -2
  22. package/dist/benchmarks/cadgenbench.d.ts +1 -4
  23. package/dist/benchmarks/cadgenbench.js +1 -2
  24. package/dist/benchmarks/commit0.d.ts +2 -5
  25. package/dist/benchmarks/commit0.js +1 -2
  26. package/dist/benchmarks/crag.d.ts +1 -4
  27. package/dist/benchmarks/crag.js +3 -3
  28. package/dist/benchmarks/crag.js.map +1 -1
  29. package/dist/benchmarks/dabstep.d.ts +2 -5
  30. package/dist/benchmarks/dabstep.js +2 -3
  31. package/dist/benchmarks/dabstep.js.map +1 -1
  32. package/dist/benchmarks/enterpriseops-gym.d.ts +2 -5
  33. package/dist/benchmarks/enterpriseops-gym.js +1 -2
  34. package/dist/benchmarks/finresearchbench.d.ts +2 -5
  35. package/dist/benchmarks/finresearchbench.js +2 -3
  36. package/dist/benchmarks/finsearchcomp.d.ts +2 -5
  37. package/dist/benchmarks/finsearchcomp.js +4 -4
  38. package/dist/benchmarks/finsearchcomp.js.map +1 -1
  39. package/dist/benchmarks/frames.d.ts +3 -19
  40. package/dist/benchmarks/frames.js +13 -39
  41. package/dist/benchmarks/frames.js.map +1 -1
  42. package/dist/benchmarks/hotpotqa.d.ts +4 -14
  43. package/dist/benchmarks/hotpotqa.js +12 -32
  44. package/dist/benchmarks/hotpotqa.js.map +1 -1
  45. package/dist/benchmarks/humaneval.d.ts +9 -12
  46. package/dist/benchmarks/humaneval.js +2 -3
  47. package/dist/benchmarks/humaneval.js.map +1 -1
  48. package/dist/benchmarks/mcad-bench.d.ts +13 -16
  49. package/dist/benchmarks/mcad-bench.js +2 -3
  50. package/dist/benchmarks/mcad-bench.js.map +1 -1
  51. package/dist/benchmarks/mcad-cq-bench.d.ts +17 -20
  52. package/dist/benchmarks/mcad-cq-bench.js +2 -3
  53. package/dist/benchmarks/mcad-cq-bench.js.map +1 -1
  54. package/dist/benchmarks/mcad-cq-golds.d.ts +2 -5
  55. package/dist/benchmarks/mcad-cq-golds.js +1 -2
  56. package/dist/benchmarks/mcad-golds.d.ts +1 -4
  57. package/dist/benchmarks/mcad-golds.js +0 -1
  58. package/dist/benchmarks/mcad-tasks.d.ts +5 -8
  59. package/dist/benchmarks/mcad-tasks.js +7 -8
  60. package/dist/benchmarks/mcad-tasks.js.map +1 -1
  61. package/dist/benchmarks/mind2web.d.ts +3 -5
  62. package/dist/benchmarks/mind2web.js +2 -3
  63. package/dist/benchmarks/mind2web.js.map +1 -1
  64. package/dist/benchmarks/nomiracl.d.ts +1 -4
  65. package/dist/benchmarks/nomiracl.js +1 -2
  66. package/dist/benchmarks/open-rag-bench.d.ts +1 -4
  67. package/dist/benchmarks/open-rag-bench.js +3 -3
  68. package/dist/benchmarks/open-rag-bench.js.map +1 -1
  69. package/dist/benchmarks/programbench.d.ts +2 -5
  70. package/dist/benchmarks/programbench.js +1 -2
  71. package/dist/benchmarks/rag-shared.d.ts +30 -22
  72. package/dist/benchmarks/rag-shared.js +8 -2
  73. package/dist/benchmarks/rag-shared.js.map +1 -1
  74. package/dist/benchmarks/ragbench.d.ts +1 -4
  75. package/dist/benchmarks/ragbench.js +3 -3
  76. package/dist/benchmarks/ragbench.js.map +1 -1
  77. package/dist/benchmarks/simpleqa.d.ts +2 -18
  78. package/dist/benchmarks/simpleqa.js +5 -31
  79. package/dist/benchmarks/simpleqa.js.map +1 -1
  80. package/dist/benchmarks/swe-bench.d.ts +7 -10
  81. package/dist/benchmarks/swe-bench.js +4 -4
  82. package/dist/benchmarks/swe-bench.js.map +1 -1
  83. package/dist/benchmarks/t2-ragbench.d.ts +1 -4
  84. package/dist/benchmarks/t2-ragbench.js +3 -3
  85. package/dist/benchmarks/t2-ragbench.js.map +1 -1
  86. package/dist/benchmarks/tau-bench-shared.d.ts +5 -8
  87. package/dist/benchmarks/tau-bench-shared.js +4 -4
  88. package/dist/benchmarks/tau-bench-shared.js.map +1 -1
  89. package/dist/benchmarks/tau2-bench.d.ts +2 -5
  90. package/dist/benchmarks/tau2-bench.js +1 -2
  91. package/dist/benchmarks/tau3-banking.d.ts +1 -4
  92. package/dist/benchmarks/tau3-banking.js +1 -2
  93. package/dist/benchmarks/terminal-bench.d.ts +1 -4
  94. package/dist/benchmarks/terminal-bench.js +4 -4
  95. package/dist/benchmarks/terminal-bench.js.map +1 -1
  96. package/dist/benchmarks/toollm.d.ts +2 -5
  97. package/dist/benchmarks/toollm.js +1 -2
  98. package/dist/benchmarks/trata-hedge.d.ts +1 -4
  99. package/dist/benchmarks/trata-hedge.js +2 -3
  100. package/dist/benchmarks/types.d.ts +6 -9
  101. package/dist/benchmarks/webarena-verified.d.ts +2 -5
  102. package/dist/benchmarks/webarena-verified.js +1 -2
  103. package/dist/{cadbench-BRF-59Mt.js → cadbench-DhAndllg.js} +4 -6
  104. package/dist/cadbench-DhAndllg.js.map +1 -0
  105. package/dist/{cadgenbench-DXtGkuW3.js → cadgenbench-Tvk16YKT.js} +15 -5
  106. package/dist/cadgenbench-Tvk16YKT.js.map +1 -0
  107. package/dist/index.d.ts +8 -18
  108. package/dist/index.js +16 -24
  109. package/dist/index.js.map +1 -1
  110. package/dist/{router-turn-uTYO6KQ1.js → router-turn-DNbQ_GjQ.js} +2 -3
  111. package/dist/router-turn-DNbQ_GjQ.js.map +1 -0
  112. package/fixtures/pier-agent/no-model-task/pre_artifacts.sh +0 -0
  113. package/fixtures/pier-agent/no-model-task/tests/test.sh +0 -0
  114. package/package.json +10 -10
  115. package/pier_agents/tangle_candidate.py +15 -23
  116. package/scripts/run-package-tests.mjs +8 -15
  117. package/src/atom-mcp-e2e.mts +2 -2
  118. package/src/benchmarks/frames.ts +10 -44
  119. package/src/benchmarks/hotpotqa.ts +9 -29
  120. package/src/benchmarks/rag-shared.ts +12 -0
  121. package/src/benchmarks/simpleqa.ts +2 -36
  122. package/src/commit0-prereqs.sh +0 -0
  123. package/src/corpus-replay.mts +8 -8
  124. package/src/corpus-report.mts +21 -21
  125. package/src/corpus.test.mts +5 -5
  126. package/src/corpus.ts +16 -16
  127. package/src/directives.ts +0 -38
  128. package/src/examples/lean-verify.ts +1 -1
  129. package/src/gate.ts +7 -7
  130. package/src/generate-eval/certify.ts +2 -2
  131. package/src/index.ts +1 -0
  132. package/src/refine-loop.ts +5 -5
  133. package/src/resolve-client.ts +1 -1
  134. package/src/router-turn.ts +3 -11
  135. package/src/run-pool.ts +1 -1
  136. package/src/runtime-hook-recorder.ts +2 -2
  137. package/src/search-bench/tasks.ts +1 -1
  138. package/src/selector.test.mts +13 -13
  139. package/src/selector.ts +19 -19
  140. package/src/swe-bench-env.ts +4 -12
  141. package/src/swe-jail.ts +5 -156
  142. package/src/swe-structural-judge-policy.ts +3 -3
  143. package/src/swe-structural-policy.ts +3 -3
  144. package/src/swe-structural-provenance.ts +4 -4
  145. package/src/terminal-compare.ts +10 -10
  146. package/src/worker-blender.ts +2 -106
  147. package/src/worker-build123d.ts +2 -81
  148. package/tb_agents/opencode_router_agent.py +1 -1
  149. package/dist/cadbench-BRF-59Mt.js.map +0 -1
  150. package/dist/cadgenbench-DXtGkuW3.js.map +0 -1
  151. package/dist/router-turn-uTYO6KQ1.js.map +0 -1
  152. package/scripts/cadbench_prepare.py +0 -22
  153. package/scripts/cadgenbench_hard_parts.py +0 -48
  154. package/scripts/clbench_codebase_judge.py +0 -73
  155. package/scripts/render-gate-chart.mjs +0 -176
  156. package/scripts/trata-hedge/README.md +0 -57
  157. package/scripts/trata-hedge/run.sh +0 -64
  158. package/src/cloud-loop.mts +0 -156
  159. package/src/coordination-mcp-container-reach.mts +0 -182
  160. package/src/fleet.mts +0 -143
  161. package/src/hev-structural.mts +0 -697
  162. package/src/humaneval-gate.mts +0 -220
  163. package/src/mbpp-structural.mts +0 -676
  164. package/src/mcp-mount-probe.mts +0 -141
  165. package/src/profiles.ts +0 -128
  166. package/src/research-gate.mts +0 -132
  167. package/src/research-shot.ts +0 -144
  168. package/src/router-executor.ts +0 -51
  169. package/src/sandbox-run.ts +0 -108
  170. package/src/search-bench/bridge.ts +0 -182
  171. package/src/search-bench/export.mts +0 -0
  172. package/src/search-bench/parametric-check.mts +0 -78
  173. package/src/search-bench/profiles.ts +0 -113
  174. package/src/search-bench/run.mts +0 -286
  175. package/src/search-bench/tasks-fresh.ts +0 -688
  176. package/src/smoke-structural-rollout.mts +0 -415
  177. package/src/stats.mts +0 -90
  178. package/src/swe-code-improve.mts +0 -306
  179. package/src/swe-improve.mts +0 -284
  180. package/src/swe-structural.mts +0 -707
  181. package/src/tb-container-executor.mts +0 -266
  182. package/src/tb-container-executor.test.mts +0 -134
  183. package/src/tb-supervisor-sidecar.mts +0 -208
  184. package/src/trata-gepa.mts +0 -381
  185. package/src/trata-hedge-solve.mts +0 -81
  186. package/tb_agents/opencode_refine_agent.py +0 -117
  187. package/tb_agents/opencode_supervisor_agent.py +0 -239
@@ -1 +1 @@
1
- {"version":3,"file":"mcad-bench.js","names":[],"sources":["../../src/benchmarks/mcad-bench.ts"],"sourcesContent":["/**\n * MCAD adapter. Worker artifact = OpenSCAD source for a dimensioned mechanical\n * part; judge = the REAL OpenSCAD kernel (compile + ASCII-STL export) followed by\n * pure-TS mesh measurement against the task's `McadSpec`. No LLM, no self-report:\n * the part either has the stated extents, volume, body count and holes, or it does\n * not.\n *\n * Pipeline, in order, and every stage is a hard fact about the produced mesh:\n * 1. compile : `xvfb-run -a openscad --export-format=asciistl -o out.stl` exits 0\n * 2. watertight : every undirected edge shared by exactly two faces (2-manifold)\n * 3. measure : bbox extents, enclosed volume (divergence theorem), connected\n * -component count (\"solids\"), triangle count\n * 4. probe : ray-parity point-in-solid at the spec's pinned hole/material\n * coordinates — this is what makes a missing or misplaced bore\n * fail, which no aggregate measure can catch\n *\n * Scoring: compile failure or a non-watertight mesh is 0 / unresolved — a mesh that\n * is not a closed solid has no well-defined volume or interior, so every downstream\n * number would be fiction. Otherwise the score is the fraction of ASSERTED spec\n * checks passed (each bbox axis, the volume band, the solids band, the triangle\n * floor, and EACH probe count as one check), and `resolved` requires all of them.\n *\n * Requires `openscad` + `xvfb-run` on PATH at JUDGE time only; `loadTasks` and the\n * geometry engine below are dependency-free and run anywhere.\n *\n * Geometry checks 1-3 are ported from supervisor-lab's `bench/cad-stl-gate.ts`\n * (edge-key manifold parity + signed-tetrahedron volume). Ported, not imported:\n * these packages do not share a dependency edge.\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport { MCAD_GOLDS } from './mcad-golds'\nimport { MCAD_TASKS, type McadSpec, type McadTask } from './mcad-tasks'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface Vec3 {\n x: number\n y: number\n z: number\n}\n\n/** One triangle as three vertices, in the STL's stated winding order. */\nexport type Tri = readonly [Vec3, Vec3, Vec3]\n\nexport interface McadGeometry {\n triangles: number\n /** Edges NOT shared by exactly two faces. 0 iff the surface is closed + 2-manifold. */\n openEdges: number\n watertight: boolean\n /** Zero-area faces — bad geometry even when the topology closes. */\n degenerateFaces: number\n /** Enclosed volume (absolute) via the signed-tetrahedron sum. */\n volume: number\n /** Connected components of the triangle-adjacency graph = disconnected bodies. */\n solids: number\n bbox: { min: Vec3; max: Vec3; size: Vec3 }\n}\n\n/** Coincident-vertex quantisation, in model units (mm). */\nconst VERTEX_QUANTUM = 1e-6\nconst AREA_EPS = 1e-9\nconst VOLUME_EPS = 1e-9\n\n// ---------------------------------------------------------------------------\n// Mesh parsing + measurement (ported from supervisor-lab bench/cad-stl-gate.ts)\n// ---------------------------------------------------------------------------\n\n/** Parse an ASCII STL into triangles by reading `vertex x y z` lines in groups of three. */\nexport function parseAsciiStl(stl: string): Tri[] {\n const verts: Vec3[] = []\n for (const line of stl.split('\\n')) {\n const m = line.trim().match(/^vertex\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)/i)\n if (!m) continue\n const x = Number(m[1])\n const y = Number(m[2])\n const z = Number(m[3])\n if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue\n verts.push({ x, y, z })\n }\n const tris: Tri[] = []\n for (let i = 0; i + 2 < verts.length; i += 3) tris.push([verts[i]!, verts[i + 1]!, verts[i + 2]!])\n return tris\n}\n\n/** Quantise a vertex so shared edges match despite float authoring noise. */\nfunction vertexKey(v: Vec3): string {\n const r = (n: number) => (Math.round(n / VERTEX_QUANTUM) * VERTEX_QUANTUM).toFixed(6)\n return `${r(v.x)},${r(v.y)},${r(v.z)}`\n}\n\nfunction sub(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z }\n}\nfunction cross(a: Vec3, b: Vec3): Vec3 {\n return { x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x }\n}\nfunction dot(a: Vec3, b: Vec3): number {\n return a.x * b.x + a.y * b.y + a.z * b.z\n}\nfunction norm(a: Vec3): number {\n return Math.sqrt(dot(a, a))\n}\nfunction normalize(a: Vec3): Vec3 {\n const n = norm(a)\n return { x: a.x / n, y: a.y / n, z: a.z / n }\n}\n\n/** Disjoint-set over triangle indices — the \"how many separate bodies\" primitive. */\nfunction findRoot(parent: Int32Array, i: number): number {\n let r = i\n while (parent[r] !== r) r = parent[r]!\n let c = i\n while (parent[c] !== c) {\n const next = parent[c]!\n parent[c] = r\n c = next\n }\n return r\n}\n\n/**\n * Measure the closed-solid properties of a triangle soup. Pure: no I/O, no deps.\n *\n * `solids` is the number of connected components of the graph whose nodes are\n * triangles and whose edges join two triangles that share a quantised mesh edge.\n * On a watertight mesh that count IS the number of disconnected bodies (an\n * enclosed internal cavity is its own shell and counts, which is the behaviour\n * the specs want — a \"hollow\" body that is really two nested shells is not one\n * fused solid).\n */\nexport function measureMesh(tris: Tri[]): McadGeometry {\n if (tris.length === 0) {\n const zero = { x: 0, y: 0, z: 0 }\n return {\n triangles: 0,\n openEdges: 0,\n watertight: false,\n degenerateFaces: 0,\n volume: 0,\n solids: 0,\n bbox: { min: zero, max: zero, size: zero },\n }\n }\n\n const min: Vec3 = { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY }\n const max: Vec3 = { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY }\n const edgeFaces = new Map<string, number[]>()\n const parent = new Int32Array(tris.length)\n for (let i = 0; i < tris.length; i++) parent[i] = i\n let degenerateFaces = 0\n let volume6 = 0\n\n for (let i = 0; i < tris.length; i++) {\n const [a, b, c] = tris[i]!\n for (const v of [a, b, c]) {\n if (v.x < min.x) min.x = v.x\n if (v.y < min.y) min.y = v.y\n if (v.z < min.z) min.z = v.z\n if (v.x > max.x) max.x = v.x\n if (v.y > max.y) max.y = v.y\n if (v.z > max.z) max.z = v.z\n }\n if (norm(cross(sub(b, a), sub(c, a))) < AREA_EPS) degenerateFaces += 1\n volume6 += dot(a, cross(b, c))\n\n const ka = vertexKey(a)\n const kb = vertexKey(b)\n const kc = vertexKey(c)\n for (const [p, q] of [\n [ka, kb],\n [kb, kc],\n [kc, ka],\n ] as const) {\n const key = p < q ? `${p}|${q}` : `${q}|${p}`\n const seen = edgeFaces.get(key)\n if (seen) seen.push(i)\n else edgeFaces.set(key, [i])\n }\n }\n\n let openEdges = 0\n for (const faces of edgeFaces.values()) {\n if (faces.length !== 2) openEdges += 1\n // Union every face pair on this edge (a >2-face edge still connects bodies).\n const first = findRoot(parent, faces[0]!)\n for (let k = 1; k < faces.length; k++) {\n const other = findRoot(parent, faces[k]!)\n if (other !== first) parent[other] = first\n }\n }\n\n const roots = new Set<number>()\n for (let i = 0; i < tris.length; i++) roots.add(findRoot(parent, i))\n\n return {\n triangles: tris.length,\n openEdges,\n watertight: openEdges === 0,\n degenerateFaces,\n volume: Math.abs(volume6) / 6,\n solids: roots.size,\n bbox: {\n min: { ...min },\n max: { ...max },\n size: { x: max.x - min.x, y: max.y - min.y, z: max.z - min.z },\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Point-in-solid by ray parity\n// ---------------------------------------------------------------------------\n\n/**\n * Three fixed, mutually linearly-independent directions built from irrational\n * constants (sqrt(3)-1, sqrt(2)-1, 1/sqrt(5), 1/sqrt(3) and the plastic-number\n * pair 0.7548777 / 0.5698403). Their 3x3 determinant is ~1.77, so no two are\n * near-parallel and no plane contains all three.\n */\nconst RAY_DIRECTIONS: readonly Vec3[] = [\n normalize({ x: 1, y: 0.7548777, z: 0.5698403 }),\n normalize({ x: -0.7320508, y: 1, z: 0.236068 }),\n normalize({ x: 0.4472136, y: -0.5773503, z: 1 }),\n]\n\n/** Barycentric / parametric tolerances for calling a crossing \"on the boundary\". */\nconst BARY_EPS = 1e-9\nconst DET_EPS = 1e-12\nconst T_EPS = 1e-9\nconst MAX_JITTERS = 8\n\n/** Deterministic 32-bit PRNG (mulberry32) — seeded, so probes never use Math.random. */\nfunction mulberry32(seed: number): () => number {\n let a = seed >>> 0\n return () => {\n a = (a + 0x6d2b79f5) >>> 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** Stable integer hash of a probe point so its jitter sequence is reproducible. */\nfunction seedForPoint(p: Vec3, rayIndex: number): number {\n let h = 2166136261 ^ rayIndex\n for (const n of [p.x, p.y, p.z]) {\n const bits = Math.round(n * 1e6) | 0\n h = Math.imul(h ^ (bits & 0xffff), 16777619)\n h = Math.imul(h ^ ((bits >>> 16) & 0xffff), 16777619)\n }\n return h >>> 0\n}\n\ntype CastResult = { crossings: number } | { degenerate: true }\n\n/**\n * Moller-Trumbore crossing count along one ray. Returns `degenerate` when the ray\n * touches a triangle edge/vertex, lies in a triangle's plane, or starts on a face\n * — the three cases where a parity count is not trustworthy.\n */\nfunction castRay(tris: Tri[], origin: Vec3, dir: Vec3): CastResult {\n let crossings = 0\n for (const [v0, v1, v2] of tris) {\n const e1 = sub(v1, v0)\n const e2 = sub(v2, v0)\n const h = cross(dir, e2)\n const det = dot(e1, h)\n const scale = norm(e1) * norm(e2)\n if (Math.abs(det) <= DET_EPS * Math.max(scale, 1)) {\n // Ray parallel to (or inside) this triangle's plane. Only a problem when the\n // ray could actually meet the triangle; distinguishing that costs more than a\n // re-cast, so treat it as degenerate whenever the origin is near the plane.\n const n = cross(e1, e2)\n const nl = norm(n)\n if (nl > AREA_EPS && Math.abs(dot(sub(origin, v0), n)) / nl <= T_EPS) return { degenerate: true }\n continue\n }\n const f = 1 / det\n const s = sub(origin, v0)\n const u = f * dot(s, h)\n const q = cross(s, e1)\n const v = f * dot(dir, q)\n const w = 1 - u - v\n if (u < -BARY_EPS || v < -BARY_EPS || w < -BARY_EPS) continue\n const t = f * dot(e2, q)\n if (t < -T_EPS) continue\n // Inside the triangle (or within EPS of its border). Anything within EPS of a\n // border, or of the origin plane, makes the parity ambiguous.\n if (Math.abs(t) <= T_EPS) return { degenerate: true }\n if (u <= BARY_EPS || v <= BARY_EPS || w <= BARY_EPS) return { degenerate: true }\n crossings += 1\n }\n return { crossings }\n}\n\n/**\n * Point-in-solid membership by ray parity, made robust three ways.\n *\n * ROBUSTNESS ARGUMENT. A parity test is exact except on a measure-zero set: rays\n * that graze a triangle edge or vertex (the crossing is counted twice or zero\n * times), rays coplanar with a face, and origins lying on the surface. Those cases\n * are not merely rare here — they are SYSTEMATIC, because OpenSCAD emits\n * axis-aligned meshes whose vertices land on the same round millimetre lattice the\n * spec's probe coordinates come from, so an axis-aligned ray from a probe point\n * hits shared edges constantly. Three defences, in order:\n * 1. DIRECTIONS. The three fixed directions are irrational combinations, so a ray\n * from a lattice point cannot stay in an axis-aligned face plane and cannot\n * run along a lattice edge.\n * 2. DETECTION + DETERMINISTIC RE-JITTER. Grazing is DETECTED (a barycentric\n * coordinate within BARY_EPS of 0, |det| below DET_EPS with the origin in the\n * plane, or |t| within T_EPS) rather than hoped away. A detected ray is re-cast\n * with a small direction perturbation drawn from a mulberry32 PRNG seeded by\n * the probe coordinates and ray index, so the whole judge stays deterministic:\n * the same mesh and the same point always take the same sequence of re-casts.\n * 3. MAJORITY VOTE. The verdict is the majority of three independent directions,\n * so even an undetected miscount on one ray cannot flip the answer.\n * A point sitting exactly ON the surface has no correct answer; every direction\n * degenerates there and the vote falls back to whatever the jittered casts say.\n * The specs therefore place probes with >=1 mm clearance from any surface.\n */\nexport function pointInSolid(tris: Tri[], point: Vec3): boolean {\n let inside = 0\n let votes = 0\n for (let i = 0; i < RAY_DIRECTIONS.length; i++) {\n const base = RAY_DIRECTIONS[i]!\n const rand = mulberry32(seedForPoint(point, i))\n let dir = base\n for (let attempt = 0; attempt <= MAX_JITTERS; attempt++) {\n const r = castRay(tris, point, dir)\n if (!('degenerate' in r)) {\n votes += 1\n if (r.crossings % 2 === 1) inside += 1\n break\n }\n dir = normalize({\n x: base.x + (rand() - 0.5) * 1e-3,\n y: base.y + (rand() - 0.5) * 1e-3,\n z: base.z + (rand() - 0.5) * 1e-3,\n })\n }\n }\n // Every direction degenerating means the point is on the surface; call it outside\n // (fail-closed: a probe that must be inside the material will report a failure).\n if (votes === 0) return false\n return inside * 2 > votes\n}\n\n// ---------------------------------------------------------------------------\n// Spec scoring\n// ---------------------------------------------------------------------------\n\nexport interface McadCheck {\n name: string\n ok: boolean\n measured: string\n expected: string\n}\n\nexport interface McadScoring {\n checks: McadCheck[]\n failed: McadCheck[]\n score: number\n resolved: boolean\n}\n\nfunction inBand(v: number, [lo, hi]: [number, number]): boolean {\n return v >= lo && v <= hi\n}\n\nfunction fmt(n: number): string {\n return String(Math.round(n * 1000) / 1000)\n}\n\nfunction pt(p: readonly [number, number, number]): string {\n return `(${p[0]}, ${p[1]}, ${p[2]})`\n}\n\n/** Score a measured mesh against the task's spec — one named check per assertion. */\nexport function scoreAgainstSpec(geo: McadGeometry, tris: Tri[], spec: McadSpec): McadScoring {\n const checks: McadCheck[] = []\n const add = (name: string, ok: boolean, measured: string, expected: string) =>\n checks.push({ name, ok, measured, expected })\n\n for (const axis of ['x', 'y', 'z'] as const) {\n const band = spec.bbox?.[axis]\n if (!band) continue\n const got = geo.bbox.size[axis]\n add(`bbox${axis.toUpperCase()}`, inBand(got, band), fmt(got), `[${band[0]}, ${band[1]}]`)\n }\n if (spec.volume) add('volume', inBand(geo.volume, spec.volume), fmt(geo.volume), `[${spec.volume[0]}, ${spec.volume[1]}]`)\n if (spec.solids) add('solids', inBand(geo.solids, spec.solids), String(geo.solids), `[${spec.solids[0]}, ${spec.solids[1]}]`)\n if (spec.minTriangles != null)\n add('minTriangles', geo.triangles >= spec.minTriangles, String(geo.triangles), `>= ${spec.minTriangles}`)\n\n for (const [i, p] of (spec.probesInsideSolid ?? []).entries()) {\n const got = pointInSolid(tris, { x: p[0], y: p[1], z: p[2] })\n add(`probeInside[${i}] ${pt(p)}`, got, got ? 'inside' : 'outside', 'inside')\n }\n for (const [i, p] of (spec.probesOutsideSolid ?? []).entries()) {\n const got = pointInSolid(tris, { x: p[0], y: p[1], z: p[2] })\n add(`probeOutside[${i}] ${pt(p)}`, !got, got ? 'inside' : 'outside', 'outside')\n }\n\n const failed = checks.filter((c) => !c.ok)\n const score = checks.length ? (checks.length - failed.length) / checks.length : 0\n return { checks, failed, score, resolved: checks.length > 0 && failed.length === 0 }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\n/** Task metadata carried onto every `BenchTask`, so the judge needs no lookup table. */\nexport interface McadTaskMeta extends Record<string, unknown> {\n spec: McadSpec\n source: string\n calibrated: boolean\n}\n\n/** Run openscad under xvfb (it wants a GL context even headless). */\nasync function openscad(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> {\n return execFileAsync('xvfb-run', ['-a', 'openscad', ...args], {\n cwd,\n maxBuffer: 1024 * 1024 * 64,\n timeout: 600_000,\n })\n}\n\n/**\n * Strip a markdown fence if the model wrapped its answer in one. The prompt asks\n * for bare source; a fenced answer is a formatting slip, not a geometry failure,\n * and the geometric gate downstream is unchanged either way.\n */\nexport function stripCodeFence(artifact: string): string {\n const trimmed = artifact.trim()\n const fenced = /^```[a-zA-Z]*\\n([\\s\\S]*?)\\n?```$/.exec(trimmed)\n return (fenced ? fenced[1]! : trimmed).trim()\n}\n\n/** Compile OpenSCAD source and measure the resulting mesh. Judge-time only. */\nexport async function compileAndMeasure(\n src: string,\n): Promise<{ ok: true; geo: McadGeometry; tris: Tri[]; stlPath: string } | { ok: false; detail: string }> {\n const dir = await mkdtemp(join(tmpdir(), 'mcad-'))\n const scadPath = join(dir, 'model.scad')\n const stlPath = join(dir, 'model.stl')\n await writeFile(scadPath, `${src}\\n`)\n\n try {\n await openscad(['--export-format=asciistl', '-o', stlPath, scadPath], dir)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { ok: false, detail: `compile failed: ${msg.slice(0, 400)}` }\n }\n\n let stl: string\n try {\n stl = await readFile(stlPath, 'utf8')\n } catch {\n return { ok: false, detail: 'compiled but produced no STL (empty geometry)' }\n }\n const tris = parseAsciiStl(stl)\n if (tris.length === 0) return { ok: false, detail: 'STL parsed to zero triangles (empty geometry)' }\n return { ok: true, geo: measureMesh(tris), tris, stlPath }\n}\n\nexport function createMcadBenchAdapter(): BenchmarkAdapter {\n return {\n name: 'mcad',\n\n async preflight() {\n try {\n await execFileAsync('xvfb-run', ['-a', 'openscad', '--version'], { timeout: 30_000 })\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(\n `mcad preflight failed: ${msg}\\n` +\n 'Fix: install OpenSCAD + Xvfb (Debian/Ubuntu: sudo apt-get install -y openscad xvfb). ' +\n 'The judge runs `xvfb-run -a openscad --export-format=asciistl -o out.stl model.scad` — both must be on PATH.',\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let tasks: McadTask[] = MCAD_TASKS\n if (opts.ids) tasks = tasks.filter((t) => opts.ids?.includes(t.id))\n if (opts.limit != null) tasks = tasks.slice(0, opts.limit)\n return tasks.map(\n (t): BenchTask => ({\n id: t.id,\n prompt: t.prompt,\n metadata: { spec: t.spec, source: t.source, calibrated: t.calibrated } satisfies McadTaskMeta,\n }),\n )\n },\n\n async goldArtifact(task: BenchTask) {\n return MCAD_GOLDS[task.id]\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const spec = (task.metadata as McadTaskMeta | undefined)?.spec\n if (!spec) return { resolved: false, score: 0, detail: `task ${task.id} carries no mcad spec` }\n\n const src = stripCodeFence(artifact)\n if (!src) return { resolved: false, score: 0, detail: 'empty artifact' }\n\n const built = await compileAndMeasure(src)\n if (!built.ok) return { resolved: false, score: 0, detail: built.detail }\n\n const { geo, tris, stlPath } = built\n if (!geo.watertight) {\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({\n gate: 'watertight',\n failed: [\n {\n name: 'watertight',\n measured: `${geo.openEdges} edge(s) not shared by exactly two faces`,\n expected: '0 open edges (closed 2-manifold solid)',\n },\n ],\n geo: { triangles: geo.triangles, degenerateFaces: geo.degenerateFaces },\n stlPath,\n }),\n }\n }\n\n const scored = scoreAgainstSpec(geo, tris, spec)\n return {\n resolved: scored.resolved,\n score: scored.score,\n detail: JSON.stringify({\n failed: scored.failed.map((c) => ({ name: c.name, measured: c.measured, expected: c.expected })),\n checks: Object.fromEntries(scored.checks.map((c) => [c.name, c.ok])),\n geo: {\n triangles: geo.triangles,\n solids: geo.solids,\n volume: +geo.volume.toFixed(2),\n degenerateFaces: geo.degenerateFaces,\n bbox: {\n x: +geo.bbox.size.x.toFixed(3),\n y: +geo.bbox.size.y.toFixed(3),\n z: +geo.bbox.size.z.toFixed(3),\n },\n },\n stlPath,\n }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,gBAAgB,UAAU,QAAQ;;AA0BxC,MAAM,iBAAiB;AACvB,MAAM,WAAW;;AAQjB,SAAgB,cAAc,KAAoB;CAChD,MAAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,IAAI,MAAM,IAAI,GAAG;EAClC,MAAM,IAAI,KAAK,KAAK,CAAC,CAAC,MAAM,kCAAkC;EAC9D,IAAI,CAAC,GAAG;EACR,MAAM,IAAI,OAAO,EAAE,EAAE;EACrB,MAAM,IAAI,OAAO,EAAE,EAAE;EACrB,MAAM,IAAI,OAAO,EAAE,EAAE;EACrB,IAAI,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,GAAG;EACvE,MAAM,KAAK;GAAE;GAAG;GAAG;EAAE,CAAC;CACxB;CACA,MAAM,OAAc,CAAC;CACrB,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,MAAM,QA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C,IAAI,KAAK,KAAK,EAAE,QAAQ,CAAC;MAC/B;KACF;KACA;IACF,CAAC;GACH;EACF;CACF;AACF"}
1
+ {"version":3,"file":"mcad-bench.js","names":[],"sources":["../../src/benchmarks/mcad-bench.ts"],"sourcesContent":["/**\n * MCAD adapter. Worker artifact = OpenSCAD source for a dimensioned mechanical\n * part; judge = the REAL OpenSCAD kernel (compile + ASCII-STL export) followed by\n * pure-TS mesh measurement against the task's `McadSpec`. No LLM, no self-report:\n * the part either has the stated extents, volume, body count and holes, or it does\n * not.\n *\n * Pipeline, in order, and every stage is a hard fact about the produced mesh:\n * 1. compile : `xvfb-run -a openscad --export-format=asciistl -o out.stl` exits 0\n * 2. watertight : every undirected edge shared by exactly two faces (2-manifold)\n * 3. measure : bbox extents, enclosed volume (divergence theorem), connected\n * -component count (\"solids\"), triangle count\n * 4. probe : ray-parity point-in-solid at the spec's pinned hole/material\n * coordinates — this is what makes a missing or misplaced bore\n * fail, which no aggregate measure can catch\n *\n * Scoring: compile failure or a non-watertight mesh is 0 / unresolved — a mesh that\n * is not a closed solid has no well-defined volume or interior, so every downstream\n * number would be fiction. Otherwise the score is the fraction of ASSERTED spec\n * checks passed (each bbox axis, the volume band, the solids band, the triangle\n * floor, and EACH probe count as one check), and `resolved` requires all of them.\n *\n * Requires `openscad` + `xvfb-run` on PATH at JUDGE time only; `loadTasks` and the\n * geometry engine below are dependency-free and run anywhere.\n *\n * Geometry checks 1-3 are ported from supervisor-lab's `bench/cad-stl-gate.ts`\n * (edge-key manifold parity + signed-tetrahedron volume). Ported, not imported:\n * these packages do not share a dependency edge.\n */\n\nimport { execFile } from 'node:child_process'\nimport { mkdtemp, readFile, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\nimport { promisify } from 'node:util'\nimport { MCAD_GOLDS } from './mcad-golds'\nimport { MCAD_TASKS, type McadSpec, type McadTask } from './mcad-tasks'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface Vec3 {\n x: number\n y: number\n z: number\n}\n\n/** One triangle as three vertices, in the STL's stated winding order. */\nexport type Tri = readonly [Vec3, Vec3, Vec3]\n\nexport interface McadGeometry {\n triangles: number\n /** Edges NOT shared by exactly two faces. 0 iff the surface is closed + 2-manifold. */\n openEdges: number\n watertight: boolean\n /** Zero-area faces — bad geometry even when the topology closes. */\n degenerateFaces: number\n /** Enclosed volume (absolute) via the signed-tetrahedron sum. */\n volume: number\n /** Connected components of the triangle-adjacency graph = disconnected bodies. */\n solids: number\n bbox: { min: Vec3; max: Vec3; size: Vec3 }\n}\n\n/** Coincident-vertex quantisation, in model units (mm). */\nconst VERTEX_QUANTUM = 1e-6\nconst AREA_EPS = 1e-9\nconst VOLUME_EPS = 1e-9\n\n// ---------------------------------------------------------------------------\n// Mesh parsing + measurement (ported from supervisor-lab bench/cad-stl-gate.ts)\n// ---------------------------------------------------------------------------\n\n/** Parse an ASCII STL into triangles by reading `vertex x y z` lines in groups of three. */\nexport function parseAsciiStl(stl: string): Tri[] {\n const verts: Vec3[] = []\n for (const line of stl.split('\\n')) {\n const m = line.trim().match(/^vertex\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)/i)\n if (!m) continue\n const x = Number(m[1])\n const y = Number(m[2])\n const z = Number(m[3])\n if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) continue\n verts.push({ x, y, z })\n }\n const tris: Tri[] = []\n for (let i = 0; i + 2 < verts.length; i += 3) tris.push([verts[i]!, verts[i + 1]!, verts[i + 2]!])\n return tris\n}\n\n/** Quantise a vertex so shared edges match despite float authoring noise. */\nfunction vertexKey(v: Vec3): string {\n const r = (n: number) => (Math.round(n / VERTEX_QUANTUM) * VERTEX_QUANTUM).toFixed(6)\n return `${r(v.x)},${r(v.y)},${r(v.z)}`\n}\n\nfunction sub(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z }\n}\nfunction cross(a: Vec3, b: Vec3): Vec3 {\n return { x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x }\n}\nfunction dot(a: Vec3, b: Vec3): number {\n return a.x * b.x + a.y * b.y + a.z * b.z\n}\nfunction norm(a: Vec3): number {\n return Math.sqrt(dot(a, a))\n}\nfunction normalize(a: Vec3): Vec3 {\n const n = norm(a)\n return { x: a.x / n, y: a.y / n, z: a.z / n }\n}\n\n/** Disjoint-set over triangle indices — the \"how many separate bodies\" primitive. */\nfunction findRoot(parent: Int32Array, i: number): number {\n let r = i\n while (parent[r] !== r) r = parent[r]!\n let c = i\n while (parent[c] !== c) {\n const next = parent[c]!\n parent[c] = r\n c = next\n }\n return r\n}\n\n/**\n * Measure the closed-solid properties of a triangle soup. Pure: no I/O, no deps.\n *\n * `solids` is the number of connected components of the graph whose nodes are\n * triangles and whose edges join two triangles that share a quantised mesh edge.\n * On a watertight mesh that count IS the number of disconnected bodies (an\n * enclosed internal cavity is its own shell and counts, which is the behaviour\n * the specs want — a \"hollow\" body that is really two nested shells is not one\n * fused solid).\n */\nexport function measureMesh(tris: Tri[]): McadGeometry {\n if (tris.length === 0) {\n const zero = { x: 0, y: 0, z: 0 }\n return {\n triangles: 0,\n openEdges: 0,\n watertight: false,\n degenerateFaces: 0,\n volume: 0,\n solids: 0,\n bbox: { min: zero, max: zero, size: zero },\n }\n }\n\n const min: Vec3 = { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY }\n const max: Vec3 = { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY }\n const edgeFaces = new Map<string, number[]>()\n const parent = new Int32Array(tris.length)\n for (let i = 0; i < tris.length; i++) parent[i] = i\n let degenerateFaces = 0\n let volume6 = 0\n\n for (let i = 0; i < tris.length; i++) {\n const [a, b, c] = tris[i]!\n for (const v of [a, b, c]) {\n if (v.x < min.x) min.x = v.x\n if (v.y < min.y) min.y = v.y\n if (v.z < min.z) min.z = v.z\n if (v.x > max.x) max.x = v.x\n if (v.y > max.y) max.y = v.y\n if (v.z > max.z) max.z = v.z\n }\n if (norm(cross(sub(b, a), sub(c, a))) < AREA_EPS) degenerateFaces += 1\n volume6 += dot(a, cross(b, c))\n\n const ka = vertexKey(a)\n const kb = vertexKey(b)\n const kc = vertexKey(c)\n for (const [p, q] of [\n [ka, kb],\n [kb, kc],\n [kc, ka],\n ] as const) {\n const key = p < q ? `${p}|${q}` : `${q}|${p}`\n const seen = edgeFaces.get(key)\n if (seen) seen.push(i)\n else edgeFaces.set(key, [i])\n }\n }\n\n let openEdges = 0\n for (const faces of edgeFaces.values()) {\n if (faces.length !== 2) openEdges += 1\n // Union every face pair on this edge (a >2-face edge still connects bodies).\n const first = findRoot(parent, faces[0]!)\n for (let k = 1; k < faces.length; k++) {\n const other = findRoot(parent, faces[k]!)\n if (other !== first) parent[other] = first\n }\n }\n\n const roots = new Set<number>()\n for (let i = 0; i < tris.length; i++) roots.add(findRoot(parent, i))\n\n return {\n triangles: tris.length,\n openEdges,\n watertight: openEdges === 0,\n degenerateFaces,\n volume: Math.abs(volume6) / 6,\n solids: roots.size,\n bbox: {\n min: { ...min },\n max: { ...max },\n size: { x: max.x - min.x, y: max.y - min.y, z: max.z - min.z },\n },\n }\n}\n\n// ---------------------------------------------------------------------------\n// Point-in-solid by ray parity\n// ---------------------------------------------------------------------------\n\n/**\n * Three fixed, mutually linearly-independent directions built from irrational\n * constants (sqrt(3)-1, sqrt(2)-1, 1/sqrt(5), 1/sqrt(3) and the plastic-number\n * pair 0.7548777 / 0.5698403). Their 3x3 determinant is ~1.77, so no two are\n * near-parallel and no plane contains all three.\n */\nconst RAY_DIRECTIONS: readonly Vec3[] = [\n normalize({ x: 1, y: 0.7548777, z: 0.5698403 }),\n normalize({ x: -0.7320508, y: 1, z: 0.236068 }),\n normalize({ x: 0.4472136, y: -0.5773503, z: 1 }),\n]\n\n/** Barycentric / parametric tolerances for calling a crossing \"on the boundary\". */\nconst BARY_EPS = 1e-9\nconst DET_EPS = 1e-12\nconst T_EPS = 1e-9\nconst MAX_JITTERS = 8\n\n/** Deterministic 32-bit PRNG (mulberry32) — seeded, so probes never use Math.random. */\nfunction mulberry32(seed: number): () => number {\n let a = seed >>> 0\n return () => {\n a = (a + 0x6d2b79f5) >>> 0\n let t = a\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** Stable integer hash of a probe point so its jitter sequence is reproducible. */\nfunction seedForPoint(p: Vec3, rayIndex: number): number {\n let h = 2166136261 ^ rayIndex\n for (const n of [p.x, p.y, p.z]) {\n const bits = Math.round(n * 1e6) | 0\n h = Math.imul(h ^ (bits & 0xffff), 16777619)\n h = Math.imul(h ^ ((bits >>> 16) & 0xffff), 16777619)\n }\n return h >>> 0\n}\n\ntype CastResult = { crossings: number } | { degenerate: true }\n\n/**\n * Moller-Trumbore crossing count along one ray. Returns `degenerate` when the ray\n * touches a triangle edge/vertex, lies in a triangle's plane, or starts on a face\n * — the three cases where a parity count is not trustworthy.\n */\nfunction castRay(tris: Tri[], origin: Vec3, dir: Vec3): CastResult {\n let crossings = 0\n for (const [v0, v1, v2] of tris) {\n const e1 = sub(v1, v0)\n const e2 = sub(v2, v0)\n const h = cross(dir, e2)\n const det = dot(e1, h)\n const scale = norm(e1) * norm(e2)\n if (Math.abs(det) <= DET_EPS * Math.max(scale, 1)) {\n // Ray parallel to (or inside) this triangle's plane. Only a problem when the\n // ray could actually meet the triangle; distinguishing that costs more than a\n // re-cast, so treat it as degenerate whenever the origin is near the plane.\n const n = cross(e1, e2)\n const nl = norm(n)\n if (nl > AREA_EPS && Math.abs(dot(sub(origin, v0), n)) / nl <= T_EPS) return { degenerate: true }\n continue\n }\n const f = 1 / det\n const s = sub(origin, v0)\n const u = f * dot(s, h)\n const q = cross(s, e1)\n const v = f * dot(dir, q)\n const w = 1 - u - v\n if (u < -BARY_EPS || v < -BARY_EPS || w < -BARY_EPS) continue\n const t = f * dot(e2, q)\n if (t < -T_EPS) continue\n // Inside the triangle (or within EPS of its border). Anything within EPS of a\n // border, or of the origin plane, makes the parity ambiguous.\n if (Math.abs(t) <= T_EPS) return { degenerate: true }\n if (u <= BARY_EPS || v <= BARY_EPS || w <= BARY_EPS) return { degenerate: true }\n crossings += 1\n }\n return { crossings }\n}\n\n/**\n * Point-in-solid membership by ray parity, made robust three ways.\n *\n * ROBUSTNESS ARGUMENT. A parity test is exact except on a measure-zero set: rays\n * that graze a triangle edge or vertex (the crossing is counted twice or zero\n * times), rays coplanar with a face, and origins lying on the surface. Those cases\n * are not merely rare here — they are SYSTEMATIC, because OpenSCAD emits\n * axis-aligned meshes whose vertices land on the same round millimetre lattice the\n * spec's probe coordinates come from, so an axis-aligned ray from a probe point\n * hits shared edges constantly. Three defences, in order:\n * 1. DIRECTIONS. The three fixed directions are irrational combinations, so a ray\n * from a lattice point cannot stay in an axis-aligned face plane and cannot\n * run along a lattice edge.\n * 2. DETECTION + DETERMINISTIC RE-JITTER. Grazing is DETECTED (a barycentric\n * coordinate within BARY_EPS of 0, |det| below DET_EPS with the origin in the\n * plane, or |t| within T_EPS) rather than hoped away. A detected ray is re-cast\n * with a small direction perturbation drawn from a mulberry32 PRNG seeded by\n * the probe coordinates and ray index, so the whole judge stays deterministic:\n * the same mesh and the same point always take the same sequence of re-casts.\n * 3. MAJORITY VOTE. The verdict is the majority of three independent directions,\n * so even an undetected miscount on one ray cannot flip the answer.\n * A point sitting exactly ON the surface has no correct answer; every direction\n * degenerates there and the vote falls back to whatever the jittered casts say.\n * The specs therefore place probes with >=1 mm clearance from any surface.\n */\nexport function pointInSolid(tris: Tri[], point: Vec3): boolean {\n let inside = 0\n let votes = 0\n for (let i = 0; i < RAY_DIRECTIONS.length; i++) {\n const base = RAY_DIRECTIONS[i]!\n const rand = mulberry32(seedForPoint(point, i))\n let dir = base\n for (let attempt = 0; attempt <= MAX_JITTERS; attempt++) {\n const r = castRay(tris, point, dir)\n if (!('degenerate' in r)) {\n votes += 1\n if (r.crossings % 2 === 1) inside += 1\n break\n }\n dir = normalize({\n x: base.x + (rand() - 0.5) * 1e-3,\n y: base.y + (rand() - 0.5) * 1e-3,\n z: base.z + (rand() - 0.5) * 1e-3,\n })\n }\n }\n // Every direction degenerating means the point is on the surface; call it outside\n // (fail-closed: a probe that must be inside the material will report a failure).\n if (votes === 0) return false\n return inside * 2 > votes\n}\n\n// ---------------------------------------------------------------------------\n// Spec scoring\n// ---------------------------------------------------------------------------\n\nexport interface McadCheck {\n name: string\n ok: boolean\n measured: string\n expected: string\n}\n\nexport interface McadScoring {\n checks: McadCheck[]\n failed: McadCheck[]\n score: number\n resolved: boolean\n}\n\nfunction inBand(v: number, [lo, hi]: [number, number]): boolean {\n return v >= lo && v <= hi\n}\n\nfunction fmt(n: number): string {\n return String(Math.round(n * 1000) / 1000)\n}\n\nfunction pt(p: readonly [number, number, number]): string {\n return `(${p[0]}, ${p[1]}, ${p[2]})`\n}\n\n/** Score a measured mesh against the task's spec — one named check per assertion. */\nexport function scoreAgainstSpec(geo: McadGeometry, tris: Tri[], spec: McadSpec): McadScoring {\n const checks: McadCheck[] = []\n const add = (name: string, ok: boolean, measured: string, expected: string) =>\n checks.push({ name, ok, measured, expected })\n\n for (const axis of ['x', 'y', 'z'] as const) {\n const band = spec.bbox?.[axis]\n if (!band) continue\n const got = geo.bbox.size[axis]\n add(`bbox${axis.toUpperCase()}`, inBand(got, band), fmt(got), `[${band[0]}, ${band[1]}]`)\n }\n if (spec.volume) add('volume', inBand(geo.volume, spec.volume), fmt(geo.volume), `[${spec.volume[0]}, ${spec.volume[1]}]`)\n if (spec.solids) add('solids', inBand(geo.solids, spec.solids), String(geo.solids), `[${spec.solids[0]}, ${spec.solids[1]}]`)\n if (spec.minTriangles != null)\n add('minTriangles', geo.triangles >= spec.minTriangles, String(geo.triangles), `>= ${spec.minTriangles}`)\n\n for (const [i, p] of (spec.probesInsideSolid ?? []).entries()) {\n const got = pointInSolid(tris, { x: p[0], y: p[1], z: p[2] })\n add(`probeInside[${i}] ${pt(p)}`, got, got ? 'inside' : 'outside', 'inside')\n }\n for (const [i, p] of (spec.probesOutsideSolid ?? []).entries()) {\n const got = pointInSolid(tris, { x: p[0], y: p[1], z: p[2] })\n add(`probeOutside[${i}] ${pt(p)}`, !got, got ? 'inside' : 'outside', 'outside')\n }\n\n const failed = checks.filter((c) => !c.ok)\n const score = checks.length ? (checks.length - failed.length) / checks.length : 0\n return { checks, failed, score, resolved: checks.length > 0 && failed.length === 0 }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\n/** Task metadata carried onto every `BenchTask`, so the judge needs no lookup table. */\nexport interface McadTaskMeta extends Record<string, unknown> {\n spec: McadSpec\n source: string\n calibrated: boolean\n}\n\n/** Run openscad under xvfb (it wants a GL context even headless). */\nasync function openscad(args: string[], cwd: string): Promise<{ stdout: string; stderr: string }> {\n return execFileAsync('xvfb-run', ['-a', 'openscad', ...args], {\n cwd,\n maxBuffer: 1024 * 1024 * 64,\n timeout: 600_000,\n })\n}\n\n/**\n * Strip a markdown fence if the model wrapped its answer in one. The prompt asks\n * for bare source; a fenced answer is a formatting slip, not a geometry failure,\n * and the geometric gate downstream is unchanged either way.\n */\nexport function stripCodeFence(artifact: string): string {\n const trimmed = artifact.trim()\n const fenced = /^```[a-zA-Z]*\\n([\\s\\S]*?)\\n?```$/.exec(trimmed)\n return (fenced ? fenced[1]! : trimmed).trim()\n}\n\n/** Compile OpenSCAD source and measure the resulting mesh. Judge-time only. */\nexport async function compileAndMeasure(\n src: string,\n): Promise<{ ok: true; geo: McadGeometry; tris: Tri[]; stlPath: string } | { ok: false; detail: string }> {\n const dir = await mkdtemp(join(tmpdir(), 'mcad-'))\n const scadPath = join(dir, 'model.scad')\n const stlPath = join(dir, 'model.stl')\n await writeFile(scadPath, `${src}\\n`)\n\n try {\n await openscad(['--export-format=asciistl', '-o', stlPath, scadPath], dir)\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n return { ok: false, detail: `compile failed: ${msg.slice(0, 400)}` }\n }\n\n let stl: string\n try {\n stl = await readFile(stlPath, 'utf8')\n } catch {\n return { ok: false, detail: 'compiled but produced no STL (empty geometry)' }\n }\n const tris = parseAsciiStl(stl)\n if (tris.length === 0) return { ok: false, detail: 'STL parsed to zero triangles (empty geometry)' }\n return { ok: true, geo: measureMesh(tris), tris, stlPath }\n}\n\nexport function createMcadBenchAdapter(): BenchmarkAdapter {\n return {\n name: 'mcad',\n\n async preflight() {\n try {\n await execFileAsync('xvfb-run', ['-a', 'openscad', '--version'], { timeout: 30_000 })\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err)\n throw new Error(\n `mcad preflight failed: ${msg}\\n` +\n 'Fix: install OpenSCAD + Xvfb (Debian/Ubuntu: sudo apt-get install -y openscad xvfb). ' +\n 'The judge runs `xvfb-run -a openscad --export-format=asciistl -o out.stl model.scad` — both must be on PATH.',\n )\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let tasks: McadTask[] = MCAD_TASKS\n if (opts.ids) tasks = tasks.filter((t) => opts.ids?.includes(t.id))\n if (opts.limit != null) tasks = tasks.slice(0, opts.limit)\n return tasks.map(\n (t): BenchTask => ({\n id: t.id,\n prompt: t.prompt,\n metadata: { spec: t.spec, source: t.source, calibrated: t.calibrated } satisfies McadTaskMeta,\n }),\n )\n },\n\n async goldArtifact(task: BenchTask) {\n return MCAD_GOLDS[task.id]\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const spec = (task.metadata as McadTaskMeta | undefined)?.spec\n if (!spec) return { resolved: false, score: 0, detail: `task ${task.id} carries no mcad spec` }\n\n const src = stripCodeFence(artifact)\n if (!src) return { resolved: false, score: 0, detail: 'empty artifact' }\n\n const built = await compileAndMeasure(src)\n if (!built.ok) return { resolved: false, score: 0, detail: built.detail }\n\n const { geo, tris, stlPath } = built\n if (!geo.watertight) {\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({\n gate: 'watertight',\n failed: [\n {\n name: 'watertight',\n measured: `${geo.openEdges} edge(s) not shared by exactly two faces`,\n expected: '0 open edges (closed 2-manifold solid)',\n },\n ],\n geo: { triangles: geo.triangles, degenerateFaces: geo.degenerateFaces },\n stlPath,\n }),\n }\n }\n\n const scored = scoreAgainstSpec(geo, tris, spec)\n return {\n resolved: scored.resolved,\n score: scored.score,\n detail: JSON.stringify({\n failed: scored.failed.map((c) => ({ name: c.name, measured: c.measured, expected: c.expected })),\n checks: Object.fromEntries(scored.checks.map((c) => [c.name, c.ok])),\n geo: {\n triangles: geo.triangles,\n solids: geo.solids,\n volume: +geo.volume.toFixed(2),\n degenerateFaces: geo.degenerateFaces,\n bbox: {\n x: +geo.bbox.size.x.toFixed(3),\n y: +geo.bbox.size.y.toFixed(3),\n z: +geo.bbox.size.z.toFixed(3),\n },\n },\n stlPath,\n }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,gBAAgB,UAAU,QAAQ;;AA0BxC,MAAM,iBAAiB;AACvB,MAAM,WAAW;;AAQjB,SAAgB,cAAc,KAAoB;CAChD,MAAM,QAAgB,CAAC;CACvB,KAAK,MAAM,QAAQ,IAAI,MAAM,IAAI,GAAG;EAClC,MAAM,IAAI,KAAK,KAAK,CAAC,CAAC,MAAM,kCAAkC;EAC9D,IAAI,CAAC,GAAG;EACR,MAAM,IAAI,OAAO,EAAE,EAAE;EACrB,MAAM,IAAI,OAAO,EAAE,EAAE;EACrB,MAAM,IAAI,OAAO,EAAE,EAAE;EACrB,IAAI,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,SAAS,CAAC,GAAG;EACvE,MAAM,KAAK;GAAE;GAAG;GAAG;EAAE,C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C7B,GAAG,CAAC,IAAI,KAAK,KAAK,EAAE,QAAQ,CAAC;OAC7B,GAAG,CAAC,IAAI,KAAK,KAAK,EAAE,QAAQ,CAAC;MAC/B;KACF;KACA;IACF,CAAC;GACH;EACF;CACF;AACF"}
@@ -1,16 +1,15 @@
1
1
  import { BenchmarkAdapter } from "./types.js";
2
2
  import { McadTask } from "./mcad-tasks.js";
3
3
  import { McadGeometry, McadScoring, Tri } from "./mcad-bench.js";
4
- //#region src/benchmarks/mcad-cq-bench.d.ts
5
4
  /** Package-relative venv, resolved through `_harness`'s bench-root lookup. */
6
- declare const CADQUERY_VENV = ".venv-cadquery";
5
+ export declare const CADQUERY_VENV = ".venv-cadquery";
7
6
  /** Files the worker's script must leave in its working directory. */
8
- declare const STL_NAME = "part.stl";
9
- declare const STEP_NAME = "part.step";
7
+ export declare const STL_NAME = "part.stl";
8
+ export declare const STEP_NAME = "part.step";
10
9
  /** Every ISO 10303-21 exchange file (a "STEP file") starts with this token. */
11
- declare const STEP_MAGIC = "ISO-10303-21";
10
+ export declare const STEP_MAGIC = "ISO-10303-21";
12
11
  /** Hard deadline for one worker script. A hang is a miss, not a stall. */
13
- declare const MCAD_CQ_TIMEOUT_MS = 120000;
12
+ export declare const MCAD_CQ_TIMEOUT_MS = 120000;
14
13
  /**
15
14
  * The exact, VERIFIED install command. Two pins here are load-bearing and neither
16
15
  * is optional on a current host:
@@ -20,21 +19,21 @@ declare const MCAD_CQ_TIMEOUT_MS = 120000;
20
19
  * `np.bool8` — removed in numpy 2. Without the pin `import cadquery` raises
21
20
  * `AttributeError: module 'numpy' has no attribute 'bool8'` at import time.
22
21
  */
23
- declare const CADQUERY_INSTALL_FIX: string;
22
+ export declare const CADQUERY_INSTALL_FIX: string;
24
23
  /**
25
24
  * Resolve the CadQuery interpreter. Never falls back to a system `python`: a
26
25
  * silent fallback would either fail deep inside a worker script or — worse — run
27
26
  * against a different CadQuery than the golds were calibrated on.
28
27
  */
29
- declare function resolveCadqueryPython(env?: Readonly<{
28
+ export declare function resolveCadqueryPython(env?: Readonly<{
30
29
  MCAD_CQ_PYTHON?: string;
31
30
  }>): string;
32
31
  /** The one message shape for "there is no usable interpreter" — HARNESS.md style. */
33
- declare function cadqueryMissingError(python: string, cause?: string): Error;
32
+ export declare function cadqueryMissingError(python: string, cause?: string): Error;
34
33
  /** v2 replacement for `MCAD_DELIVERABLE`. */
35
- declare const MCAD_CQ_DELIVERABLE: string;
34
+ export declare const MCAD_CQ_DELIVERABLE: string;
36
35
  /** v2 replacement for `MCAD_DELIVERABLE_MULTIBODY` — task 10 only, same reason as v1. */
37
- declare const MCAD_CQ_DELIVERABLE_MULTIBODY: string;
36
+ export declare const MCAD_CQ_DELIVERABLE_MULTIBODY: string;
38
37
  /**
39
38
  * Swap the deliverable preamble for the CadQuery one, leaving the upstream
40
39
  * dimensional text byte-identical. Fails loud rather than guessing: a task whose
@@ -42,16 +41,16 @@ declare const MCAD_CQ_DELIVERABLE_MULTIBODY: string;
42
41
  * shape, and silently shipping a prompt with two contradictory deliverables is
43
42
  * exactly the failure this function exists to prevent.
44
43
  */
45
- declare function toCadQueryPrompt(task: McadTask): string;
44
+ export declare function toCadQueryPrompt(task: McadTask): string;
46
45
  /**
47
46
  * Reject anything that is not an ASCII STL. A binary STL also opens with the
48
47
  * bytes `solid` often enough that the header alone is not a test, so the NUL scan
49
48
  * carries the decision: ASCII STL is printable text end to end.
50
49
  */
51
- declare function asciiStlProblem(buf: Buffer): string | undefined;
50
+ export declare function asciiStlProblem(buf: Buffer): string | undefined;
52
51
  /** `part.step` exists AND opens with the ISO 10303-21 magic. Reads 12 bytes, not the file. */
53
- declare function stepFileEmitted(path: string): Promise<boolean>;
54
- type McadCqBuild = {
52
+ export declare function stepFileEmitted(path: string): Promise<boolean>;
53
+ export type McadCqBuild = {
55
54
  ok: true;
56
55
  geo: McadGeometry;
57
56
  tris: Tri[];
@@ -69,14 +68,12 @@ type McadCqBuild = {
69
68
  * Throws (never scores) when there is no usable interpreter — an absent toolchain
70
69
  * is an operator defect, and scoring it 0 would silently poison a whole corpus.
71
70
  */
72
- declare function runAndMeasureCadQuery(src: string, timeoutMs?: number): Promise<McadCqBuild>;
71
+ export declare function runAndMeasureCadQuery(src: string, timeoutMs?: number): Promise<McadCqBuild>;
73
72
  /**
74
73
  * Append the STEP-delivery check to a v1 scoring and recompute. It is one check
75
74
  * among the spec's, deliberately: the upstream benchmark's deliverable IS a STEP
76
75
  * file, so failing to produce one costs exactly what failing a dimension costs.
77
76
  */
78
- declare function withStepCheck(scored: McadScoring, stepEmitted: boolean): McadScoring;
79
- declare function createMcadCqAdapter(): BenchmarkAdapter;
80
- //#endregion
81
- export { CADQUERY_INSTALL_FIX, CADQUERY_VENV, MCAD_CQ_DELIVERABLE, MCAD_CQ_DELIVERABLE_MULTIBODY, MCAD_CQ_TIMEOUT_MS, McadCqBuild, STEP_MAGIC, STEP_NAME, STL_NAME, asciiStlProblem, cadqueryMissingError, createMcadCqAdapter, resolveCadqueryPython, runAndMeasureCadQuery, stepFileEmitted, toCadQueryPrompt, withStepCheck };
77
+ export declare function withStepCheck(scored: McadScoring, stepEmitted: boolean): McadScoring;
78
+ export declare function createMcadCqAdapter(): BenchmarkAdapter;
82
79
  //# sourceMappingURL=mcad-cq-bench.d.ts.map
@@ -8,7 +8,7 @@ import { execFile } from "node:child_process";
8
8
  import { existsSync } from "node:fs";
9
9
  import { tmpdir } from "node:os";
10
10
  import { promisify } from "node:util";
11
- //#region src/benchmarks/mcad-cq-bench.ts
11
+ // src/benchmarks/mcad-cq-bench.ts
12
12
  /**
13
13
  * MCAD-CQ adapter — the v2 runner that closes v1's format deviation.
14
14
  *
@@ -184,7 +184,7 @@ async function runAndMeasureCadQuery(src, timeoutMs = MCAD_CQ_TIMEOUT_MS) {
184
184
  env: scriptEnv(dir),
185
185
  timeout: timeoutMs,
186
186
  killSignal: "SIGKILL",
187
- maxBuffer: 1024 * 1024 * 64
187
+ maxBuffer: 67108864
188
188
  });
189
189
  } catch (err) {
190
190
  const e = err;
@@ -333,7 +333,6 @@ function createMcadCqAdapter() {
333
333
  }
334
334
  };
335
335
  }
336
- //#endregion
337
336
  export { CADQUERY_INSTALL_FIX, CADQUERY_VENV, MCAD_CQ_DELIVERABLE, MCAD_CQ_DELIVERABLE_MULTIBODY, MCAD_CQ_TIMEOUT_MS, STEP_MAGIC, STEP_NAME, STL_NAME, asciiStlProblem, cadqueryMissingError, createMcadCqAdapter, resolveCadqueryPython, runAndMeasureCadQuery, stepFileEmitted, toCadQueryPrompt, withStepCheck };
338
337
 
339
338
  //# sourceMappingURL=mcad-cq-bench.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcad-cq-bench.js","names":[],"sources":["../../src/benchmarks/mcad-cq-bench.ts"],"sourcesContent":["/**\n * MCAD-CQ adapter — the v2 runner that closes v1's format deviation.\n *\n * `mcad-tasks.ts` states the deviation in its header: the upstream text-to-cad\n * benchmark asks for STEP, and OpenSCAD cannot emit it, so v1 grades an STL that\n * OpenSCAD compiled. This adapter runs the SAME ten dimensioned parts against the\n * SAME spec assertions, but the worker's artifact is a Python CadQuery script that\n * must export BOTH `part.step` (the format upstream actually asks for) and\n * `part.stl` (ASCII — what the geometry engine measures).\n *\n * Everything downstream of the mesh is v1's engine, IMPORTED not copied:\n * `parseAsciiStl` / `measureMesh` / `pointInSolid` / `scoreAgainstSpec` /\n * `stripCodeFence` all come from `./mcad-bench`, and the specs come from\n * `./mcad-tasks`. Only two things differ:\n * 1. the deliverable preamble (Python + CadQuery, not OpenSCAD) — applied by\n * mapping at load time, so v1's prompt strings are never mutated;\n * 2. one EXTRA scored check, `stepEmitted`: `part.step` exists and begins with\n * `ISO-10303-21` (the ISO 10303-21 exchange-file magic every STEP file\n * opens with). It is scored like any other assertion, so a script that\n * emits only the mesh cannot reach 1.0 no matter how correct its geometry.\n *\n * Pipeline, in order:\n * 1. run : `<python> model.py` in a fresh temp dir, 120 s hard deadline\n * 2. deliver : `part.stl` exists and is ASCII (a binary STL is a miss, not a\n * parse problem — the prompt pins the format)\n * 3. watertight: every undirected edge shared by exactly two faces\n * 4. measure : bbox / volume / connected components / triangle count\n * 5. probe : ray-parity point-in-solid at the spec's pinned coordinates\n * 6. step : the `stepEmitted` check above\n * A non-watertight mesh scores 0 for the same reason as v1: an unclosed surface\n * has no well-defined interior, so every downstream number would be fiction.\n *\n * SAFETY, stated once and deliberately. The judge EXECUTES the worker's Python on\n * the host with no sandbox. That is the same trust level as v1 handing arbitrary\n * source to the OpenSCAD kernel, and it carries the same rule: run this judge only\n * on artifacts you would be willing to run by hand. The child process is given a\n * scrubbed environment — no inherited variables beyond `PATH`, `HOME`/`TMPDIR`\n * pointed at the scratch directory, and proxy variables pointed at a closed port —\n * which DISCOURAGES network access and keeps host secrets out of the script's\n * reach. It is not a network jail and does not claim to be one; put the judge in a\n * container if you need that guarantee.\n *\n * Requires an interpreter that can `import cadquery` at JUDGE time only.\n * Resolution order: `MCAD_CQ_PYTHON` (absolute path) → `bench/.venv-cadquery/bin/python`\n * → throw with the exact install command (see `CADQUERY_INSTALL_FIX`).\n */\n\nimport { execFile } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { mkdtemp, open, readFile, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join } from 'node:path'\nimport { promisify } from 'node:util'\nimport { venvPythonAt } from './_harness'\nimport {\n type McadCheck,\n type McadGeometry,\n type McadScoring,\n type McadTaskMeta,\n type Tri,\n measureMesh,\n parseAsciiStl,\n scoreAgainstSpec,\n stripCodeFence,\n} from './mcad-bench'\nimport { MCAD_CQ_GOLDS, MCAD_CQ_UNCALIBRATED } from './mcad-cq-golds'\nimport { MCAD_DELIVERABLE, MCAD_DELIVERABLE_MULTIBODY, MCAD_TASKS, type McadTask } from './mcad-tasks'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst execFileAsync = promisify(execFile)\n\n/** Package-relative venv, resolved through `_harness`'s bench-root lookup. */\nexport const CADQUERY_VENV = '.venv-cadquery'\n\n/** Files the worker's script must leave in its working directory. */\nexport const STL_NAME = 'part.stl'\nexport const STEP_NAME = 'part.step'\n\n/** Every ISO 10303-21 exchange file (a \"STEP file\") starts with this token. */\nexport const STEP_MAGIC = 'ISO-10303-21'\n\n/** Hard deadline for one worker script. A hang is a miss, not a stall. */\nexport const MCAD_CQ_TIMEOUT_MS = 120_000\n\n/**\n * The exact, VERIFIED install command. Two pins here are load-bearing and neither\n * is optional on a current host:\n * - `--python 3.12`: cadquery 2.4.0 resolves to `cadquery-ocp` 7.7.2, which ships\n * wheels for cp38–cp312 only. On a default CPython 3.13 the resolve fails.\n * - `'numpy<2'`: cadquery 2.4.0 pins `nptyping==2.0.1`, whose module body reads\n * `np.bool8` — removed in numpy 2. Without the pin `import cadquery` raises\n * `AttributeError: module 'numpy' has no attribute 'bool8'` at import time.\n */\nexport const CADQUERY_INSTALL_FIX =\n 'Fix: create the isolated CadQuery venv (needs `uv`):\\n' +\n ' cd bench && uv venv --python 3.12 .venv-cadquery \\\\\\n' +\n \" && uv pip install --python .venv-cadquery/bin/python 'cadquery==2.4.0' 'numpy<2'\\n\" +\n 'Both pins are required: cadquery-ocp 7.7.2 has no cp313 wheel, and cadquery 2.4.0 pins ' +\n \"nptyping 2.0.1, which reads the numpy-1.x-only `np.bool8` at import.\\n\" +\n 'Or set MCAD_CQ_PYTHON to the ABSOLUTE path of any interpreter that can `import cadquery`.'\n\n/**\n * Resolve the CadQuery interpreter. Never falls back to a system `python`: a\n * silent fallback would either fail deep inside a worker script or — worse — run\n * against a different CadQuery than the golds were calibrated on.\n */\nexport function resolveCadqueryPython(\n env: Readonly<{ MCAD_CQ_PYTHON?: string }> = process.env,\n): string {\n const configured = env.MCAD_CQ_PYTHON\n if (configured === undefined) return venvPythonAt(CADQUERY_VENV)\n if (!isAbsolute(configured)) throw new Error(`MCAD_CQ_PYTHON must be an absolute path (got ${JSON.stringify(configured)})`)\n return configured\n}\n\n/** The one message shape for \"there is no usable interpreter\" — HARNESS.md style. */\nexport function cadqueryMissingError(python: string, cause?: string): Error {\n return new Error(\n `mcad-cq: no CadQuery interpreter at ${python}${cause ? `\\n${cause}` : ''}\\n${CADQUERY_INSTALL_FIX}`,\n )\n}\n\n// ---------------------------------------------------------------------------\n// Prompt mapping (v1's prompt strings are read, never written)\n// ---------------------------------------------------------------------------\n\nconst CQ_EXPORT_STEP = `cq.exporters.export(result, \"${STEP_NAME}\")`\nconst CQ_EXPORT_STL =\n `cq.exporters.export(result, \"${STL_NAME}\", exportType=\"STL\", opt={\"ascii\": True}, ` +\n 'tolerance=0.01, angularTolerance=0.05)'\n\n/** Shared tail: what the script must WRITE, which is the whole deliverable contract. */\nconst CQ_DELIVERABLE_TAIL =\n 'The script must run standalone under `python model.py` and write BOTH of these files into its ' +\n `current working directory: \\`${STEP_NAME}\\` (STEP) and \\`${STL_NAME}\\` (ASCII STL, not binary). ` +\n 'Export with exactly these two lines:\\n' +\n ` ${CQ_EXPORT_STEP}\\n` +\n ` ${CQ_EXPORT_STL}\\n` +\n 'Those tessellation tolerances are what make round features accurate — do not coarsen them. ' +\n 'Reply with ONLY the Python code.'\n\n/** v2 replacement for `MCAD_DELIVERABLE`. */\nexport const MCAD_CQ_DELIVERABLE =\n 'Author a Python script using CadQuery (units: mm) that builds exactly this part as one fused solid ' +\n 'and binds it to a variable named `result`. ' +\n CQ_DELIVERABLE_TAIL\n\n/** v2 replacement for `MCAD_DELIVERABLE_MULTIBODY` — task 10 only, same reason as v1. */\nexport const MCAD_CQ_DELIVERABLE_MULTIBODY =\n 'Author a Python script using CadQuery (units: mm) that builds exactly this assembly as the separate ' +\n 'solid bodies listed below and binds them to a variable named `result` (a `cq.Compound` of those bodies, ' +\n 'or a Workplane holding all of them). The bodies must stay disjoint — no two of them may touch or ' +\n 'intersect. ' +\n CQ_DELIVERABLE_TAIL\n\n/**\n * Swap the deliverable preamble for the CadQuery one, leaving the upstream\n * dimensional text byte-identical. Fails loud rather than guessing: a task whose\n * prompt does not open with one of v1's two known preambles means v1 changed\n * shape, and silently shipping a prompt with two contradictory deliverables is\n * exactly the failure this function exists to prevent.\n */\nexport function toCadQueryPrompt(task: McadTask): string {\n for (const [v1, v2] of [\n [MCAD_DELIVERABLE_MULTIBODY, MCAD_CQ_DELIVERABLE_MULTIBODY],\n [MCAD_DELIVERABLE, MCAD_CQ_DELIVERABLE],\n ] as const) {\n if (task.prompt.startsWith(v1)) return v2 + task.prompt.slice(v1.length)\n }\n throw new Error(\n `mcad-cq: task ${task.id} does not open with a known mcad deliverable preamble; ` +\n 'mcad-tasks.ts changed shape and the CadQuery prompt mapping must be updated with it',\n )\n}\n\n// ---------------------------------------------------------------------------\n// Running the worker's script\n// ---------------------------------------------------------------------------\n\n/**\n * The child's whole environment. Nothing is inherited except `PATH` (the\n * interpreter needs its own toolchain on it) and `LANG`. `HOME`/`TMPDIR` point at\n * the scratch dir so the script cannot write to the operator's home, and the proxy\n * variables point at port 9 (discard), which every mainstream HTTP client honours.\n * DISCOURAGEMENT, not a jail — see the file header.\n */\nfunction scriptEnv(dir: string): NodeJS.ProcessEnv {\n const blackhole = 'http://127.0.0.1:9'\n return {\n PATH: process.env.PATH ?? '/usr/bin:/bin',\n LANG: process.env.LANG ?? 'C.UTF-8',\n HOME: dir,\n TMPDIR: dir,\n PYTHONDONTWRITEBYTECODE: '1',\n PYTHONHASHSEED: '0',\n http_proxy: blackhole,\n https_proxy: blackhole,\n HTTP_PROXY: blackhole,\n HTTPS_PROXY: blackhole,\n no_proxy: '',\n NO_PROXY: '',\n }\n}\n\n/**\n * Reject anything that is not an ASCII STL. A binary STL also opens with the\n * bytes `solid` often enough that the header alone is not a test, so the NUL scan\n * carries the decision: ASCII STL is printable text end to end.\n */\nexport function asciiStlProblem(buf: Buffer): string | undefined {\n if (buf.length === 0) return `${STL_NAME} is empty`\n if (buf.includes(0)) return `${STL_NAME} is not ASCII (contains NUL bytes — it looks like a binary STL)`\n const head = buf.subarray(0, 64).toString('latin1')\n if (!/^\\s*solid\\b/.test(head)) return `${STL_NAME} does not start with \"solid\" (got ${JSON.stringify(head.slice(0, 32))})`\n if (!/\\bfacet\\s+normal\\b/.test(buf.toString('utf8'))) return `${STL_NAME} contains no \"facet normal\" records`\n return undefined\n}\n\n/** `part.step` exists AND opens with the ISO 10303-21 magic. Reads 12 bytes, not the file. */\nexport async function stepFileEmitted(path: string): Promise<boolean> {\n let handle: Awaited<ReturnType<typeof open>>\n try {\n handle = await open(path, 'r')\n } catch {\n return false\n }\n try {\n const buf = Buffer.alloc(STEP_MAGIC.length)\n const { bytesRead } = await handle.read(buf, 0, buf.length, 0)\n return bytesRead === buf.length && buf.toString('latin1') === STEP_MAGIC\n } finally {\n await handle.close()\n }\n}\n\nexport type McadCqBuild =\n | { ok: true; geo: McadGeometry; tris: Tri[]; dir: string; stlPath: string; stepEmitted: boolean }\n | { ok: false; detail: string; dir: string; stepEmitted: boolean }\n\n/**\n * Run one CadQuery script and measure what it delivered. Judge-time only.\n * Throws (never scores) when there is no usable interpreter — an absent toolchain\n * is an operator defect, and scoring it 0 would silently poison a whole corpus.\n */\nexport async function runAndMeasureCadQuery(src: string, timeoutMs = MCAD_CQ_TIMEOUT_MS): Promise<McadCqBuild> {\n const python = resolveCadqueryPython()\n if (!existsSync(python)) throw cadqueryMissingError(python)\n\n const dir = await mkdtemp(join(tmpdir(), 'mcad-cq-'))\n const stlPath = join(dir, STL_NAME)\n const stepPath = join(dir, STEP_NAME)\n await writeFile(join(dir, 'model.py'), `${src}\\n`)\n\n const fail = async (detail: string): Promise<McadCqBuild> => ({\n ok: false,\n detail,\n dir,\n stepEmitted: await stepFileEmitted(stepPath),\n })\n\n try {\n await execFileAsync(python, ['model.py'], {\n cwd: dir,\n env: scriptEnv(dir),\n timeout: timeoutMs,\n killSignal: 'SIGKILL',\n maxBuffer: 1024 * 1024 * 64,\n })\n } catch (err) {\n const e = err as NodeJS.ErrnoException & { killed?: boolean; stderr?: string }\n if (e.killed) return fail(`script timed out after ${timeoutMs} ms and was killed`)\n const stderr = (e.stderr ?? e.message ?? '').trim()\n return fail(`script failed: ${stderr.slice(-800)}`)\n }\n\n let stl: Buffer\n try {\n stl = await readFile(stlPath)\n } catch {\n return fail(`script wrote no ${STL_NAME} in its working directory`)\n }\n const bad = asciiStlProblem(stl)\n if (bad) return fail(bad)\n\n const tris = parseAsciiStl(stl.toString('utf8'))\n if (tris.length === 0) return fail(`${STL_NAME} parsed to zero triangles (empty geometry)`)\n\n return {\n ok: true,\n geo: measureMesh(tris),\n tris,\n dir,\n stlPath,\n stepEmitted: await stepFileEmitted(stepPath),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Scoring\n// ---------------------------------------------------------------------------\n\n/**\n * Append the STEP-delivery check to a v1 scoring and recompute. It is one check\n * among the spec's, deliberately: the upstream benchmark's deliverable IS a STEP\n * file, so failing to produce one costs exactly what failing a dimension costs.\n */\nexport function withStepCheck(scored: McadScoring, stepEmitted: boolean): McadScoring {\n const check: McadCheck = {\n name: 'stepEmitted',\n ok: stepEmitted,\n measured: stepEmitted ? `${STEP_NAME} starts with ${STEP_MAGIC}` : `no ${STEP_NAME} starting with ${STEP_MAGIC}`,\n expected: `${STEP_NAME} exists and starts with ${STEP_MAGIC}`,\n }\n const checks = [...scored.checks, check]\n const failed = checks.filter((c) => !c.ok)\n return { checks, failed, score: (checks.length - failed.length) / checks.length, resolved: failed.length === 0 }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport function createMcadCqAdapter(): BenchmarkAdapter {\n return {\n name: 'mcad-cq',\n\n async preflight() {\n const python = resolveCadqueryPython()\n if (!existsSync(python)) throw cadqueryMissingError(python)\n try {\n await execFileAsync(python, ['-c', 'import cadquery; print(cadquery.__version__)'], {\n timeout: 300_000,\n env: scriptEnv(tmpdir()),\n })\n } catch (err) {\n const e = err as NodeJS.ErrnoException & { stderr?: string }\n throw cadqueryMissingError(python, `\\`import cadquery\\` failed: ${(e.stderr ?? e.message ?? '').trim().slice(-800)}`)\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let tasks: McadTask[] = MCAD_TASKS\n if (opts.ids) tasks = tasks.filter((t) => opts.ids?.includes(t.id))\n if (opts.limit != null) tasks = tasks.slice(0, opts.limit)\n return tasks.map(\n (t): BenchTask => ({\n id: t.id,\n prompt: toCadQueryPrompt(t),\n metadata: {\n spec: t.spec,\n source: t.source,\n // Calibration is per-ADAPTER: a task calibrated against the OpenSCAD\n // gold says nothing about whether a CadQuery gold reaches 1.0 here.\n calibrated: t.calibrated && !MCAD_CQ_UNCALIBRATED.has(t.id),\n } satisfies McadTaskMeta,\n }),\n )\n },\n\n async goldArtifact(task: BenchTask) {\n return MCAD_CQ_GOLDS[task.id]\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const spec = (task.metadata as McadTaskMeta | undefined)?.spec\n if (!spec) return { resolved: false, score: 0, detail: `task ${task.id} carries no mcad spec` }\n\n const src = stripCodeFence(artifact)\n if (!src) return { resolved: false, score: 0, detail: 'empty artifact' }\n\n const built = await runAndMeasureCadQuery(src)\n if (!built.ok) {\n return { resolved: false, score: 0, detail: `${built.detail} [dir ${built.dir}, stepEmitted ${built.stepEmitted}]` }\n }\n\n const { geo, tris, stlPath, stepEmitted, dir } = built\n if (!geo.watertight) {\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({\n gate: 'watertight',\n failed: [\n {\n name: 'watertight',\n measured: `${geo.openEdges} edge(s) not shared by exactly two faces`,\n expected: '0 open edges (closed 2-manifold solid)',\n },\n ],\n geo: { triangles: geo.triangles, degenerateFaces: geo.degenerateFaces },\n stepEmitted,\n stlPath,\n dir,\n }),\n }\n }\n\n const scored = withStepCheck(scoreAgainstSpec(geo, tris, spec), stepEmitted)\n return {\n resolved: scored.resolved,\n score: scored.score,\n detail: JSON.stringify({\n failed: scored.failed.map((c) => ({ name: c.name, measured: c.measured, expected: c.expected })),\n checks: Object.fromEntries(scored.checks.map((c) => [c.name, c.ok])),\n geo: {\n triangles: geo.triangles,\n solids: geo.solids,\n volume: +geo.volume.toFixed(2),\n degenerateFaces: geo.degenerateFaces,\n bbox: {\n x: +geo.bbox.size.x.toFixed(3),\n y: +geo.bbox.size.y.toFixed(3),\n z: +geo.bbox.size.z.toFixed(3),\n },\n },\n stepEmitted,\n stlPath,\n dir,\n }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,gBAAgB,UAAU,QAAQ;;AAGxC,MAAa,gBAAgB;;AAG7B,MAAa,WAAW;AACxB,MAAa,YAAY;;AAGzB,MAAa,aAAa;;AAG1B,MAAa,qBAAqB;;;;;;;;;;AAWlC,MAAa,uBACX;;;;;;AAYF,SAAgB,sBACd,MAA6C,QAAQ,KAC7C;CACR,MAAM,aAAa,IAAI;CACvB,IAAI,eAAe,KAAA,GAAW,OAAO,aAAa,aAAa;CAC/D,IAAI,CAAC,WAAW,UAAU,GAAG,MAAM,IAAI,MAAM,gDAAgD,KAAK,UAAU,UAAU,EAAE,EAAE;CAC1H,OAAO;AACT;;AAGA,SAAgB,qBAAqB,QAAgB,OAAuB;CAC1E,uBAAO,IAAI,MACT,uCAAuC,SAAS,QAAQ,KAAK,UAAU,GAAG,IAAI,sBAChF;AACF;;AAYA,MAAM,sBACJ,gIACgC,UAAU,kBAAkB,SAAS;IAEhE,gCAVgD,UAAU,IAU3C,MACf,gCAT2B,SAAS,kFAStB;;AAKrB,MAAa,sBACX,mJAEA;;AAGF,MAAa,gCACX,6TAIA;;;;;;;;AASF,SAAgB,iBAAiB,MAAwB;CACvD,KAAK,MAAM,CAAC,IAAI,OAAO,CACrB,CAAC,4BAA4B,6BAA6B,GAC1D,CAAC,kBAAkB,mBAAmB,CACxC,GACE,IAAI,KAAK,OAAO,WAAW,EAAE,GAAG,OAAO,KAAK,KAAK,OAAO,MAAM,GAAG,MAAM;CAEzE,MAA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;GACH;EACF;CACF;AACF"}
1
+ {"version":3,"file":"mcad-cq-bench.js","names":[],"sources":["../../src/benchmarks/mcad-cq-bench.ts"],"sourcesContent":["/**\n * MCAD-CQ adapter — the v2 runner that closes v1's format deviation.\n *\n * `mcad-tasks.ts` states the deviation in its header: the upstream text-to-cad\n * benchmark asks for STEP, and OpenSCAD cannot emit it, so v1 grades an STL that\n * OpenSCAD compiled. This adapter runs the SAME ten dimensioned parts against the\n * SAME spec assertions, but the worker's artifact is a Python CadQuery script that\n * must export BOTH `part.step` (the format upstream actually asks for) and\n * `part.stl` (ASCII — what the geometry engine measures).\n *\n * Everything downstream of the mesh is v1's engine, IMPORTED not copied:\n * `parseAsciiStl` / `measureMesh` / `pointInSolid` / `scoreAgainstSpec` /\n * `stripCodeFence` all come from `./mcad-bench`, and the specs come from\n * `./mcad-tasks`. Only two things differ:\n * 1. the deliverable preamble (Python + CadQuery, not OpenSCAD) — applied by\n * mapping at load time, so v1's prompt strings are never mutated;\n * 2. one EXTRA scored check, `stepEmitted`: `part.step` exists and begins with\n * `ISO-10303-21` (the ISO 10303-21 exchange-file magic every STEP file\n * opens with). It is scored like any other assertion, so a script that\n * emits only the mesh cannot reach 1.0 no matter how correct its geometry.\n *\n * Pipeline, in order:\n * 1. run : `<python> model.py` in a fresh temp dir, 120 s hard deadline\n * 2. deliver : `part.stl` exists and is ASCII (a binary STL is a miss, not a\n * parse problem — the prompt pins the format)\n * 3. watertight: every undirected edge shared by exactly two faces\n * 4. measure : bbox / volume / connected components / triangle count\n * 5. probe : ray-parity point-in-solid at the spec's pinned coordinates\n * 6. step : the `stepEmitted` check above\n * A non-watertight mesh scores 0 for the same reason as v1: an unclosed surface\n * has no well-defined interior, so every downstream number would be fiction.\n *\n * SAFETY, stated once and deliberately. The judge EXECUTES the worker's Python on\n * the host with no sandbox. That is the same trust level as v1 handing arbitrary\n * source to the OpenSCAD kernel, and it carries the same rule: run this judge only\n * on artifacts you would be willing to run by hand. The child process is given a\n * scrubbed environment — no inherited variables beyond `PATH`, `HOME`/`TMPDIR`\n * pointed at the scratch directory, and proxy variables pointed at a closed port —\n * which DISCOURAGES network access and keeps host secrets out of the script's\n * reach. It is not a network jail and does not claim to be one; put the judge in a\n * container if you need that guarantee.\n *\n * Requires an interpreter that can `import cadquery` at JUDGE time only.\n * Resolution order: `MCAD_CQ_PYTHON` (absolute path) → `bench/.venv-cadquery/bin/python`\n * → throw with the exact install command (see `CADQUERY_INSTALL_FIX`).\n */\n\nimport { execFile } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { mkdtemp, open, readFile, writeFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { isAbsolute, join } from 'node:path'\nimport { promisify } from 'node:util'\nimport { venvPythonAt } from './_harness'\nimport {\n type McadCheck,\n type McadGeometry,\n type McadScoring,\n type McadTaskMeta,\n type Tri,\n measureMesh,\n parseAsciiStl,\n scoreAgainstSpec,\n stripCodeFence,\n} from './mcad-bench'\nimport { MCAD_CQ_GOLDS, MCAD_CQ_UNCALIBRATED } from './mcad-cq-golds'\nimport { MCAD_DELIVERABLE, MCAD_DELIVERABLE_MULTIBODY, MCAD_TASKS, type McadTask } from './mcad-tasks'\nimport type { BenchmarkAdapter, BenchScore, BenchTask, LoadOptions } from './types'\n\nconst execFileAsync = promisify(execFile)\n\n/** Package-relative venv, resolved through `_harness`'s bench-root lookup. */\nexport const CADQUERY_VENV = '.venv-cadquery'\n\n/** Files the worker's script must leave in its working directory. */\nexport const STL_NAME = 'part.stl'\nexport const STEP_NAME = 'part.step'\n\n/** Every ISO 10303-21 exchange file (a \"STEP file\") starts with this token. */\nexport const STEP_MAGIC = 'ISO-10303-21'\n\n/** Hard deadline for one worker script. A hang is a miss, not a stall. */\nexport const MCAD_CQ_TIMEOUT_MS = 120_000\n\n/**\n * The exact, VERIFIED install command. Two pins here are load-bearing and neither\n * is optional on a current host:\n * - `--python 3.12`: cadquery 2.4.0 resolves to `cadquery-ocp` 7.7.2, which ships\n * wheels for cp38–cp312 only. On a default CPython 3.13 the resolve fails.\n * - `'numpy<2'`: cadquery 2.4.0 pins `nptyping==2.0.1`, whose module body reads\n * `np.bool8` — removed in numpy 2. Without the pin `import cadquery` raises\n * `AttributeError: module 'numpy' has no attribute 'bool8'` at import time.\n */\nexport const CADQUERY_INSTALL_FIX =\n 'Fix: create the isolated CadQuery venv (needs `uv`):\\n' +\n ' cd bench && uv venv --python 3.12 .venv-cadquery \\\\\\n' +\n \" && uv pip install --python .venv-cadquery/bin/python 'cadquery==2.4.0' 'numpy<2'\\n\" +\n 'Both pins are required: cadquery-ocp 7.7.2 has no cp313 wheel, and cadquery 2.4.0 pins ' +\n \"nptyping 2.0.1, which reads the numpy-1.x-only `np.bool8` at import.\\n\" +\n 'Or set MCAD_CQ_PYTHON to the ABSOLUTE path of any interpreter that can `import cadquery`.'\n\n/**\n * Resolve the CadQuery interpreter. Never falls back to a system `python`: a\n * silent fallback would either fail deep inside a worker script or — worse — run\n * against a different CadQuery than the golds were calibrated on.\n */\nexport function resolveCadqueryPython(\n env: Readonly<{ MCAD_CQ_PYTHON?: string }> = process.env,\n): string {\n const configured = env.MCAD_CQ_PYTHON\n if (configured === undefined) return venvPythonAt(CADQUERY_VENV)\n if (!isAbsolute(configured)) throw new Error(`MCAD_CQ_PYTHON must be an absolute path (got ${JSON.stringify(configured)})`)\n return configured\n}\n\n/** The one message shape for \"there is no usable interpreter\" — HARNESS.md style. */\nexport function cadqueryMissingError(python: string, cause?: string): Error {\n return new Error(\n `mcad-cq: no CadQuery interpreter at ${python}${cause ? `\\n${cause}` : ''}\\n${CADQUERY_INSTALL_FIX}`,\n )\n}\n\n// ---------------------------------------------------------------------------\n// Prompt mapping (v1's prompt strings are read, never written)\n// ---------------------------------------------------------------------------\n\nconst CQ_EXPORT_STEP = `cq.exporters.export(result, \"${STEP_NAME}\")`\nconst CQ_EXPORT_STL =\n `cq.exporters.export(result, \"${STL_NAME}\", exportType=\"STL\", opt={\"ascii\": True}, ` +\n 'tolerance=0.01, angularTolerance=0.05)'\n\n/** Shared tail: what the script must WRITE, which is the whole deliverable contract. */\nconst CQ_DELIVERABLE_TAIL =\n 'The script must run standalone under `python model.py` and write BOTH of these files into its ' +\n `current working directory: \\`${STEP_NAME}\\` (STEP) and \\`${STL_NAME}\\` (ASCII STL, not binary). ` +\n 'Export with exactly these two lines:\\n' +\n ` ${CQ_EXPORT_STEP}\\n` +\n ` ${CQ_EXPORT_STL}\\n` +\n 'Those tessellation tolerances are what make round features accurate — do not coarsen them. ' +\n 'Reply with ONLY the Python code.'\n\n/** v2 replacement for `MCAD_DELIVERABLE`. */\nexport const MCAD_CQ_DELIVERABLE =\n 'Author a Python script using CadQuery (units: mm) that builds exactly this part as one fused solid ' +\n 'and binds it to a variable named `result`. ' +\n CQ_DELIVERABLE_TAIL\n\n/** v2 replacement for `MCAD_DELIVERABLE_MULTIBODY` — task 10 only, same reason as v1. */\nexport const MCAD_CQ_DELIVERABLE_MULTIBODY =\n 'Author a Python script using CadQuery (units: mm) that builds exactly this assembly as the separate ' +\n 'solid bodies listed below and binds them to a variable named `result` (a `cq.Compound` of those bodies, ' +\n 'or a Workplane holding all of them). The bodies must stay disjoint — no two of them may touch or ' +\n 'intersect. ' +\n CQ_DELIVERABLE_TAIL\n\n/**\n * Swap the deliverable preamble for the CadQuery one, leaving the upstream\n * dimensional text byte-identical. Fails loud rather than guessing: a task whose\n * prompt does not open with one of v1's two known preambles means v1 changed\n * shape, and silently shipping a prompt with two contradictory deliverables is\n * exactly the failure this function exists to prevent.\n */\nexport function toCadQueryPrompt(task: McadTask): string {\n for (const [v1, v2] of [\n [MCAD_DELIVERABLE_MULTIBODY, MCAD_CQ_DELIVERABLE_MULTIBODY],\n [MCAD_DELIVERABLE, MCAD_CQ_DELIVERABLE],\n ] as const) {\n if (task.prompt.startsWith(v1)) return v2 + task.prompt.slice(v1.length)\n }\n throw new Error(\n `mcad-cq: task ${task.id} does not open with a known mcad deliverable preamble; ` +\n 'mcad-tasks.ts changed shape and the CadQuery prompt mapping must be updated with it',\n )\n}\n\n// ---------------------------------------------------------------------------\n// Running the worker's script\n// ---------------------------------------------------------------------------\n\n/**\n * The child's whole environment. Nothing is inherited except `PATH` (the\n * interpreter needs its own toolchain on it) and `LANG`. `HOME`/`TMPDIR` point at\n * the scratch dir so the script cannot write to the operator's home, and the proxy\n * variables point at port 9 (discard), which every mainstream HTTP client honours.\n * DISCOURAGEMENT, not a jail — see the file header.\n */\nfunction scriptEnv(dir: string): NodeJS.ProcessEnv {\n const blackhole = 'http://127.0.0.1:9'\n return {\n PATH: process.env.PATH ?? '/usr/bin:/bin',\n LANG: process.env.LANG ?? 'C.UTF-8',\n HOME: dir,\n TMPDIR: dir,\n PYTHONDONTWRITEBYTECODE: '1',\n PYTHONHASHSEED: '0',\n http_proxy: blackhole,\n https_proxy: blackhole,\n HTTP_PROXY: blackhole,\n HTTPS_PROXY: blackhole,\n no_proxy: '',\n NO_PROXY: '',\n }\n}\n\n/**\n * Reject anything that is not an ASCII STL. A binary STL also opens with the\n * bytes `solid` often enough that the header alone is not a test, so the NUL scan\n * carries the decision: ASCII STL is printable text end to end.\n */\nexport function asciiStlProblem(buf: Buffer): string | undefined {\n if (buf.length === 0) return `${STL_NAME} is empty`\n if (buf.includes(0)) return `${STL_NAME} is not ASCII (contains NUL bytes — it looks like a binary STL)`\n const head = buf.subarray(0, 64).toString('latin1')\n if (!/^\\s*solid\\b/.test(head)) return `${STL_NAME} does not start with \"solid\" (got ${JSON.stringify(head.slice(0, 32))})`\n if (!/\\bfacet\\s+normal\\b/.test(buf.toString('utf8'))) return `${STL_NAME} contains no \"facet normal\" records`\n return undefined\n}\n\n/** `part.step` exists AND opens with the ISO 10303-21 magic. Reads 12 bytes, not the file. */\nexport async function stepFileEmitted(path: string): Promise<boolean> {\n let handle: Awaited<ReturnType<typeof open>>\n try {\n handle = await open(path, 'r')\n } catch {\n return false\n }\n try {\n const buf = Buffer.alloc(STEP_MAGIC.length)\n const { bytesRead } = await handle.read(buf, 0, buf.length, 0)\n return bytesRead === buf.length && buf.toString('latin1') === STEP_MAGIC\n } finally {\n await handle.close()\n }\n}\n\nexport type McadCqBuild =\n | { ok: true; geo: McadGeometry; tris: Tri[]; dir: string; stlPath: string; stepEmitted: boolean }\n | { ok: false; detail: string; dir: string; stepEmitted: boolean }\n\n/**\n * Run one CadQuery script and measure what it delivered. Judge-time only.\n * Throws (never scores) when there is no usable interpreter — an absent toolchain\n * is an operator defect, and scoring it 0 would silently poison a whole corpus.\n */\nexport async function runAndMeasureCadQuery(src: string, timeoutMs = MCAD_CQ_TIMEOUT_MS): Promise<McadCqBuild> {\n const python = resolveCadqueryPython()\n if (!existsSync(python)) throw cadqueryMissingError(python)\n\n const dir = await mkdtemp(join(tmpdir(), 'mcad-cq-'))\n const stlPath = join(dir, STL_NAME)\n const stepPath = join(dir, STEP_NAME)\n await writeFile(join(dir, 'model.py'), `${src}\\n`)\n\n const fail = async (detail: string): Promise<McadCqBuild> => ({\n ok: false,\n detail,\n dir,\n stepEmitted: await stepFileEmitted(stepPath),\n })\n\n try {\n await execFileAsync(python, ['model.py'], {\n cwd: dir,\n env: scriptEnv(dir),\n timeout: timeoutMs,\n killSignal: 'SIGKILL',\n maxBuffer: 1024 * 1024 * 64,\n })\n } catch (err) {\n const e = err as NodeJS.ErrnoException & { killed?: boolean; stderr?: string }\n if (e.killed) return fail(`script timed out after ${timeoutMs} ms and was killed`)\n const stderr = (e.stderr ?? e.message ?? '').trim()\n return fail(`script failed: ${stderr.slice(-800)}`)\n }\n\n let stl: Buffer\n try {\n stl = await readFile(stlPath)\n } catch {\n return fail(`script wrote no ${STL_NAME} in its working directory`)\n }\n const bad = asciiStlProblem(stl)\n if (bad) return fail(bad)\n\n const tris = parseAsciiStl(stl.toString('utf8'))\n if (tris.length === 0) return fail(`${STL_NAME} parsed to zero triangles (empty geometry)`)\n\n return {\n ok: true,\n geo: measureMesh(tris),\n tris,\n dir,\n stlPath,\n stepEmitted: await stepFileEmitted(stepPath),\n }\n}\n\n// ---------------------------------------------------------------------------\n// Scoring\n// ---------------------------------------------------------------------------\n\n/**\n * Append the STEP-delivery check to a v1 scoring and recompute. It is one check\n * among the spec's, deliberately: the upstream benchmark's deliverable IS a STEP\n * file, so failing to produce one costs exactly what failing a dimension costs.\n */\nexport function withStepCheck(scored: McadScoring, stepEmitted: boolean): McadScoring {\n const check: McadCheck = {\n name: 'stepEmitted',\n ok: stepEmitted,\n measured: stepEmitted ? `${STEP_NAME} starts with ${STEP_MAGIC}` : `no ${STEP_NAME} starting with ${STEP_MAGIC}`,\n expected: `${STEP_NAME} exists and starts with ${STEP_MAGIC}`,\n }\n const checks = [...scored.checks, check]\n const failed = checks.filter((c) => !c.ok)\n return { checks, failed, score: (checks.length - failed.length) / checks.length, resolved: failed.length === 0 }\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nexport function createMcadCqAdapter(): BenchmarkAdapter {\n return {\n name: 'mcad-cq',\n\n async preflight() {\n const python = resolveCadqueryPython()\n if (!existsSync(python)) throw cadqueryMissingError(python)\n try {\n await execFileAsync(python, ['-c', 'import cadquery; print(cadquery.__version__)'], {\n timeout: 300_000,\n env: scriptEnv(tmpdir()),\n })\n } catch (err) {\n const e = err as NodeJS.ErrnoException & { stderr?: string }\n throw cadqueryMissingError(python, `\\`import cadquery\\` failed: ${(e.stderr ?? e.message ?? '').trim().slice(-800)}`)\n }\n },\n\n async loadTasks(opts: LoadOptions = {}) {\n let tasks: McadTask[] = MCAD_TASKS\n if (opts.ids) tasks = tasks.filter((t) => opts.ids?.includes(t.id))\n if (opts.limit != null) tasks = tasks.slice(0, opts.limit)\n return tasks.map(\n (t): BenchTask => ({\n id: t.id,\n prompt: toCadQueryPrompt(t),\n metadata: {\n spec: t.spec,\n source: t.source,\n // Calibration is per-ADAPTER: a task calibrated against the OpenSCAD\n // gold says nothing about whether a CadQuery gold reaches 1.0 here.\n calibrated: t.calibrated && !MCAD_CQ_UNCALIBRATED.has(t.id),\n } satisfies McadTaskMeta,\n }),\n )\n },\n\n async goldArtifact(task: BenchTask) {\n return MCAD_CQ_GOLDS[task.id]\n },\n\n async judge(task: BenchTask, artifact: string): Promise<BenchScore> {\n const spec = (task.metadata as McadTaskMeta | undefined)?.spec\n if (!spec) return { resolved: false, score: 0, detail: `task ${task.id} carries no mcad spec` }\n\n const src = stripCodeFence(artifact)\n if (!src) return { resolved: false, score: 0, detail: 'empty artifact' }\n\n const built = await runAndMeasureCadQuery(src)\n if (!built.ok) {\n return { resolved: false, score: 0, detail: `${built.detail} [dir ${built.dir}, stepEmitted ${built.stepEmitted}]` }\n }\n\n const { geo, tris, stlPath, stepEmitted, dir } = built\n if (!geo.watertight) {\n return {\n resolved: false,\n score: 0,\n detail: JSON.stringify({\n gate: 'watertight',\n failed: [\n {\n name: 'watertight',\n measured: `${geo.openEdges} edge(s) not shared by exactly two faces`,\n expected: '0 open edges (closed 2-manifold solid)',\n },\n ],\n geo: { triangles: geo.triangles, degenerateFaces: geo.degenerateFaces },\n stepEmitted,\n stlPath,\n dir,\n }),\n }\n }\n\n const scored = withStepCheck(scoreAgainstSpec(geo, tris, spec), stepEmitted)\n return {\n resolved: scored.resolved,\n score: scored.score,\n detail: JSON.stringify({\n failed: scored.failed.map((c) => ({ name: c.name, measured: c.measured, expected: c.expected })),\n checks: Object.fromEntries(scored.checks.map((c) => [c.name, c.ok])),\n geo: {\n triangles: geo.triangles,\n solids: geo.solids,\n volume: +geo.volume.toFixed(2),\n degenerateFaces: geo.degenerateFaces,\n bbox: {\n x: +geo.bbox.size.x.toFixed(3),\n y: +geo.bbox.size.y.toFixed(3),\n z: +geo.bbox.size.z.toFixed(3),\n },\n },\n stepEmitted,\n stlPath,\n dir,\n }),\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,gBAAgB,UAAU,QAAQ;;AAGxC,MAAa,g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U;KACrB,MAAM;KACN,QAAQ,CACN;MACE,MAAM;MACN,UAAU,GAAG,IAAI,UAAU;MAC3B,UAAU;KACZ,CACF;KACA,KAAK;MAAE,WAAW,IAAI;MAAW,iBAAiB,IAAI;KAAgB;KACtE;KACA;KACA;IACF,CAAC;GACH;GAGF,MAAM,SAAS,cAAc,iBAAiB,KAAK,MAAM,IAAI,GAAG,WAAW;GAC3E,OAAO;IACL,UAAU,OAAO;IACjB,OAAO,OAAO;IACd,QAAQ,KAAK,UAAU;KACrB,QAAQ,OAAO,OAAO,KAAK,OAAO;MAAE,MAAM,EAAE;MAAM,UAAU,EAAE;MAAU,UAAU,EAAE;KAAS,EAAE;KAC/F,QAAQ,OAAO,YAAY,OAAO,OAAO,KAAK,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;KACnE,KAAK;MACH,WAAW,IAAI;MACf,QAAQ,IAAI;MACZ,QAAQ,CAAC,IAAI,OAAO,QAAQ,CAAC;MAC7B,iBAAiB,IAAI;MACrB,MAAM;OACJ,GAAG,CAAC,IAAI,KAAK,KAAK,EAAE,QAAQ,CAAC;OAC7B,GAAG,CAAC,IAAI,KAAK,KAAK,EAAE,QAAQ,CAAC;OAC7B,GAAG,CAAC,IAAI,KAAK,KAAK,EAAE,QAAQ,CAAC;MAC/B;KACF;KACA;KACA;KACA;IACF,CAAC;GACH;EACF;CACF;AACF"}
@@ -1,4 +1,3 @@
1
- //#region src/benchmarks/mcad-cq-golds.d.ts
2
1
  /**
3
2
  * MCAD-CQ gold oracles — one Python CadQuery script per task in `mcad-tasks.ts`.
4
3
  *
@@ -23,14 +22,12 @@
23
22
  * inherited verbatim from v1: task 10's ring tooth-tip diameter.
24
23
  */
25
24
  /** Gold CadQuery script per task id — preamble, body, then the two export lines. */
26
- declare const MCAD_CQ_GOLDS: Record<string, string>;
25
+ export declare const MCAD_CQ_GOLDS: Record<string, string>;
27
26
  /**
28
27
  * Task ids whose CadQuery gold does NOT reach 1.0 through this adapter. Empty
29
28
  * means every gold calibrates; an entry here is a promise that the spec was left
30
29
  * alone and the gold is the thing that fell short, with the failing check named in
31
30
  * a comment on the body above.
32
31
  */
33
- declare const MCAD_CQ_UNCALIBRATED: ReadonlySet<string>;
34
- //#endregion
35
- export { MCAD_CQ_GOLDS, MCAD_CQ_UNCALIBRATED };
32
+ export declare const MCAD_CQ_UNCALIBRATED: ReadonlySet<string>;
36
33
  //# sourceMappingURL=mcad-cq-golds.d.ts.map
@@ -1,4 +1,4 @@
1
- //#region src/benchmarks/mcad-cq-golds.ts
1
+ // src/benchmarks/mcad-cq-golds.ts
2
2
  /**
3
3
  * MCAD-CQ gold oracles — one Python CadQuery script per task in `mcad-tasks.ts`.
4
4
  *
@@ -336,7 +336,6 @@ const MCAD_CQ_GOLDS = Object.fromEntries(Object.entries(BODIES).map(([id, body])
336
336
  * a comment on the body above.
337
337
  */
338
338
  const MCAD_CQ_UNCALIBRATED = /* @__PURE__ */ new Set();
339
- //#endregion
340
339
  export { MCAD_CQ_GOLDS, MCAD_CQ_UNCALIBRATED };
341
340
 
342
341
  //# sourceMappingURL=mcad-cq-golds.js.map
@@ -1,4 +1,3 @@
1
- //#region src/benchmarks/mcad-golds.d.ts
2
1
  /**
3
2
  * MCAD gold oracles — one OpenSCAD model per task in `mcad-tasks.ts`.
4
3
  *
@@ -14,7 +13,5 @@
14
13
  * make a coplanar 9-body assembly geometrically impossible; see the comment).
15
14
  */
16
15
  /** Gold OpenSCAD source per task id. */
17
- declare const MCAD_GOLDS: Record<string, string>;
18
- //#endregion
19
- export { MCAD_GOLDS };
16
+ export declare const MCAD_GOLDS: Record<string, string>;
20
17
  //# sourceMappingURL=mcad-golds.d.ts.map
@@ -312,7 +312,6 @@ translate([0, 0, -5]) cylinder(h = 4, r = 52.5);
312
312
  for (i = [0:2]) rotate(120*i) translate([42, 0, 0]) cylinder(h = 14, d = 6);
313
313
  `.trim()
314
314
  };
315
- //#endregion
316
315
  export { MCAD_GOLDS };
317
316
 
318
317
  //# sourceMappingURL=mcad-golds.js.map
@@ -1,4 +1,3 @@
1
- //#region src/benchmarks/mcad-tasks.d.ts
2
1
  /**
3
2
  * MCAD task specs — 10 dimensioned mechanical parts adopted from the MIT-licensed
4
3
  * text-to-cad benchmark set (github.com/earthtojake/text-to-cad, `benchmarks/`).
@@ -22,7 +21,7 @@
22
21
  * missing, misplaced by more than ~1 mm, or wrong in diameter by more than ~1 mm
23
22
  * flips at least one probe.
24
23
  */
25
- interface McadSpec {
24
+ export interface McadSpec {
26
25
  /** Overall axis-aligned extents in mm, [min, max] per axis. */
27
26
  bbox?: {
28
27
  x?: [number, number];
@@ -40,7 +39,7 @@ interface McadSpec {
40
39
  /** Points (mm) that must test OUTSIDE the solid (hole/pocket/clearance present). */
41
40
  probesOutsideSolid?: Array<[number, number, number]>;
42
41
  }
43
- interface McadTask {
42
+ export interface McadTask {
44
43
  id: string;
45
44
  /** Upstream dimensional brief, verbatim, wrapped for the OpenSCAD deliverable. */
46
45
  prompt: string;
@@ -54,13 +53,11 @@ interface McadTask {
54
53
  /** Exported so a sibling adapter can SWAP this preamble for its own deliverable
55
54
  * (see `mcad-cq-bench.ts`) by prefix, instead of re-authoring ten prompts and
56
55
  * letting the two copies drift. The upstream dimensional text stays the tail. */
57
- declare const MCAD_DELIVERABLE: string;
56
+ export declare const MCAD_DELIVERABLE: string;
58
57
  /** Task 10 is an ASSEMBLY, not a part: its own text says "use separate solid bodies"
59
58
  * and its checklist pins nine of them, which the single-solid boilerplate above
60
59
  * flatly contradicts. A worker cannot satisfy both, so that task gets this
61
60
  * preamble instead; everything else about the deliverable is unchanged. */
62
- declare const MCAD_DELIVERABLE_MULTIBODY: string;
63
- declare const MCAD_TASKS: McadTask[];
64
- //#endregion
65
- export { MCAD_DELIVERABLE, MCAD_DELIVERABLE_MULTIBODY, MCAD_TASKS, McadSpec, McadTask };
61
+ export declare const MCAD_DELIVERABLE_MULTIBODY: string;
62
+ export declare const MCAD_TASKS: McadTask[];
66
63
  //# sourceMappingURL=mcad-tasks.d.ts.map
@@ -1,4 +1,4 @@
1
- //#region src/benchmarks/mcad-tasks.ts
1
+ // src/benchmarks/mcad-tasks.ts
2
2
  /** Exported so a sibling adapter can SWAP this preamble for its own deliverable
3
3
  * (see `mcad-cq-bench.ts`) by prefix, instead of re-authoring ten prompts and
4
4
  * letting the two copies drift. The upstream dimensional text stays the tail. */
@@ -253,7 +253,7 @@ const MCAD_TASKS = [
253
253
  [
254
254
  38,
255
255
  25,
256
- 15 - 8 / 2
256
+ 11
257
257
  ],
258
258
  [
259
259
  35,
@@ -270,27 +270,27 @@ const MCAD_TASKS = [
270
270
  [
271
271
  35,
272
272
  25,
273
- 15 - 8 / 2
273
+ 11
274
274
  ],
275
275
  [
276
276
  -35,
277
277
  25,
278
- 15 - 8 / 2
278
+ 11
279
279
  ],
280
280
  [
281
281
  35,
282
282
  -25,
283
- 15 - 8 / 2
283
+ 11
284
284
  ],
285
285
  [
286
286
  -35,
287
287
  -25,
288
- 15 - 8 / 2
288
+ 11
289
289
  ],
290
290
  [
291
291
  35.5,
292
292
  25,
293
- 15 - 8 / 2
293
+ 11
294
294
  ]
295
295
  ]
296
296
  }
@@ -502,7 +502,6 @@ const MCAD_TASKS = [
502
502
  }
503
503
  }
504
504
  ];
505
- //#endregion
506
505
  export { MCAD_DELIVERABLE, MCAD_DELIVERABLE_MULTIBODY, MCAD_TASKS };
507
506
 
508
507
  //# sourceMappingURL=mcad-tasks.js.map