Official Codebase of 3DCodeVerse
Python
languages: the three python build wrappers share one _wrapper_common — run_bpy_links stops writing its own
gaoypeng261681c1088e
diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.pyindex 2e72db25..29fe7d34 100644--- a/harness/codeverse3d/languages/blender/__init__.py+++ b/harness/codeverse3d/languages/blender/__init__.py@@ -675,8 +675,7 @@ def write_blender_skeleton(ws: Workspace, plan: StaticPlan, *, ground_tol_m: flo# ===================================================================== runtime-_PKG_DIR = Path(__file__).resolve().parent-WRAPPER = _PKG_DIR / "wrappers" / "run_bpy.py"+WRAPPER = Path(__file__).resolve().parent.parent / "wrappers" / "run_bpy.py"class BlenderNotFoundError(RuntimeError):diff --git a/harness/codeverse3d/languages/cadquery/__init__.py b/harness/codeverse3d/languages/cadquery/__init__.pyindex d8ff3122..3c745522 100644--- a/harness/codeverse3d/languages/cadquery/__init__.py+++ b/harness/codeverse3d/languages/cadquery/__init__.py@@ -311,8 +311,7 @@ def write_cadquery_skeleton(ws: Workspace, plan: StaticPlan) -> list[Path]:# ===================================================================== runtime-_PKG_DIR = Path(__file__).resolve().parent-WRAPPER = _PKG_DIR / "wrappers" / "run_cq.py"+WRAPPER = Path(__file__).resolve().parent.parent / "wrappers" / "run_cq.py"def cadquery_env() -> dict[str, str]:diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.pyindex cdad310a..036899b2 100644--- a/harness/codeverse3d/languages/urdf/__init__.py+++ b/harness/codeverse3d/languages/urdf/__init__.py@@ -1,5 +1,5 @@"""``urdf_blender``: bpy link meshes + hand-written URDF — lint, skeleton, FK ↔ geometry-consistency and the ``UrdfBlenderRuntime`` around ``wrappers/run_bpy_links.py``."""+consistency and the ``UrdfBlenderRuntime`` around ``languages/wrappers/run_bpy_links.py``."""from __future__ import annotations@@ -744,7 +744,7 @@ def write_skeleton(ws: Workspace, plan: ArticulatedPlan) -> list[Path]:# ===================================================================== runtime-WRAPPER = Path(__file__).resolve().parent / "wrappers" / "run_bpy_links.py"+WRAPPER = Path(__file__).resolve().parent.parent / "wrappers" / "run_bpy_links.py"REST_PENETRATION_MAX_M = 0.005FK_TOL_M = 0.001diff --git a/harness/codeverse3d/languages/urdf/wrappers/run_bpy_links.py b/harness/codeverse3d/languages/urdf/wrappers/run_bpy_links.pydeleted file mode 100644index 81c9510b..00000000--- a/harness/codeverse3d/languages/urdf/wrappers/run_bpy_links.py+++ /dev/null@@ -1,270 +0,0 @@-"""Blender-side build wrapper for the ``urdf_blender`` language (run BY THE HARNESS).-- blender -b --factory-startup --python run_bpy_links.py -- \- --script src/model.py --urdf src/robot.urdf --out artifacts/ [--rlimit-gb 12]--1. empties the scene, executes ``model.py`` (errors mapped to its line numbers),-2. takes a census of every mesh-like object (name, tris, WORLD bbox, Z-up),-3. matches URDF link names to objects (an object named exactly ``<link>`` plus- anything parented under it forms that link's mesh),-4. exports ``<out>/meshes/<link>.glb`` per link with the geometry baked in WORLD- coordinates at the authored rest pose, Z-up (``export_yup=False`` — the file- holds URDF-frame coordinates, NOT glTF Y-up), then-5. writes ``<out>/census.json`` and ``<out>/build.json``.--Self-contained on purpose: Blender's bundled python cannot import ``codeverse3d``.-"""--import argparse-import io-import json-import math-import re-import sys-import time-import traceback-import xml.etree.ElementTree as ET-from contextlib import redirect_stdout-from pathlib import Path--import bpy-from mathutils import Matrix, Vector--MESH_LIKE = {"MESH", "CURVE", "FONT", "SURFACE", "META"}---def _snake(name: str) -> str:- s = re.sub(r"[^0-9A-Za-z]+", "_", name.strip())- s = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", s)- return re.sub(r"_+", "_", s).strip("_").lower()---#: link names double as ``meshes/<link>.glb`` filename stems: plain identifiers only.-#: The lint layer states the same rule (``languages/urdf/lint._IDENT``) but only WARNs,-#: so the wrapper enforces it — ``../evil`` must be a build error, never a file written-#: outside ``meshes/``.-_SAFE_LINK = re.compile(r"[A-Za-z][A-Za-z0-9_]*")---def _bad_links(links: list[str]) -> list[str]:- """Link names that are unsafe as filenames (not plain identifiers)."""- return [name for name in links if not _SAFE_LINK.fullmatch(name or "")]---def _set_rlimit(gb: float) -> None:- try:- import resource-- lim = int(gb * 1024**3)- resource.setrlimit(resource.RLIMIT_AS, (lim, lim))- except Exception as e: # pragma: no cover- print(f"[wrapper] rlimit not applied: {e}")---def _urdf_links(urdf_path: Path) -> list[str]:- root = ET.parse(urdf_path).getroot()- return [el.get("name", "") for el in root.findall("link")]---def _exec_script(script: Path) -> dict:- """Run the agent script; return an error dict (empty on success) + captured stdout."""- code = compile(script.read_text(), str(script), "exec")- g = {"__name__": "__main__", "__file__": str(script), "__builtins__": __builtins__}- buf = io.StringIO()- err: dict = {}- try:- with redirect_stdout(buf):- exec(code, g)- except BaseException as e: # noqa: BLE001 — we report everything, including SystemExit- tb = traceback.extract_tb(e.__traceback__)- line = None- for fr in tb:- if Path(fr.filename).resolve() == script.resolve():- line = fr.lineno- err = {- "error_type": type(e).__name__,- "error_message": str(e)[:2000],- "error_line": line,- "traceback": "".join(traceback.format_exception(type(e), e, e.__traceback__))[-3000:],- }- err["script_stdout"] = buf.getvalue()[-4000:]- return err---def _world_bbox(ob) -> tuple[list, list]:- lo = [math.inf] * 3- hi = [-math.inf] * 3- for c in ob.bound_box:- w = ob.matrix_world @ Vector(c)- for i in range(3):- lo[i] = min(lo[i], w[i])- hi[i] = max(hi[i], w[i])- return lo, hi---def _evaluated_world_mesh(ob, depsgraph):- """New bpy Mesh datablock of ``ob`` (modifiers applied) in WORLD coordinates."""- ev = ob.evaluated_get(depsgraph)- me = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph)- me.transform(ob.matrix_world)- return me---def _descendants(ob) -> list:- out = []- stack = list(ob.children)- while stack:- c = stack.pop()- out.append(c)- stack.extend(c.children)- return out---def _census(depsgraph) -> list[dict]:- rows = []- for ob in bpy.data.objects:- if ob.type not in MESH_LIKE:- continue- ev = ob.evaluated_get(depsgraph)- me = ev.to_mesh()- try:- n_verts = len(me.vertices)- me.calc_loop_triangles()- n_tris = len(me.loop_triangles)- finally:- ev.to_mesh_clear()- lo, hi = _world_bbox(ob)- rows.append({- "name": ob.name, "type": ob.type, "verts": n_verts, "tris": n_tris,- "bbox_min": [round(v, 6) for v in lo], "bbox_max": [round(v, 6) for v in hi],- "parent": ob.parent.name if ob.parent else None,- "materials": [m.name for m in ob.material_slots if m.material] if hasattr(ob, "material_slots") else [],- })- return rows---def _export_link(link: str, objects: list, out_glb: Path, depsgraph) -> dict:- """Join ``objects`` (world space) into one temp object and export it as GLB."""- meshes = [_evaluated_world_mesh(ob, depsgraph) for ob in objects]- temp_objs = []- for i, me in enumerate(meshes):- o = bpy.data.objects.new(f"__c3v_{link}_{i}", me)- bpy.context.scene.collection.objects.link(o)- temp_objs.append(o)- bpy.ops.object.select_all(action="DESELECT")- for o in temp_objs:- o.select_set(True)- bpy.context.view_layer.objects.active = temp_objs[0]- if len(temp_objs) > 1:- bpy.ops.object.join()- joined = bpy.context.view_layer.objects.active- joined.name = link- joined.matrix_world = Matrix.Identity(4)- bpy.ops.object.select_all(action="DESELECT")- joined.select_set(True)- joined.data.calc_loop_triangles()- lo, hi = _world_bbox(joined)- info = {- "mesh": f"meshes/{link}.glb", "tris": len(joined.data.loop_triangles), "verts": len(joined.data.vertices),- "bbox_min": [round(v, 6) for v in lo], "bbox_max": [round(v, 6) for v in hi],- "objects": [o.name for o in objects],- }- out_glb.parent.mkdir(parents=True, exist_ok=True)- bpy.ops.export_scene.gltf(- filepath=str(out_glb), export_format="GLB", use_selection=True, export_yup=False, export_apply=True,- export_materials="EXPORT", export_extras=False, export_animations=False, export_cameras=False,- export_lights=False, export_normals=True, export_texcoords=True, export_skins=False, export_morph=False,- )- bpy.data.objects.remove(joined, do_unlink=True)- return info---def main() -> None:- argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []- ap = argparse.ArgumentParser()- ap.add_argument("--script", required=True)- ap.add_argument("--urdf", required=True)- ap.add_argument("--out", required=True)- ap.add_argument("--rlimit-gb", type=float, default=12.0)- args = ap.parse_args(argv)- t0 = time.time()- script, urdf, out = Path(args.script).resolve(), Path(args.urdf).resolve(), Path(args.out).resolve()- out.mkdir(parents=True, exist_ok=True)- _set_rlimit(args.rlimit_gb)- build: dict = {"ok": False, "language": "urdf_blender", "error_type": "", "error_message": "",- "error_file": "src/model.py", "error_line": None, "extra_paths": {}}- census: dict = {"objects": [], "links": {}, "unmatched_objects": [], "missing_links": [], "hints": {}}-- def finish() -> None:- build["duration_ms"] = int((time.time() - t0) * 1000)- (out / "census.json").write_text(json.dumps(census, indent=1))- (out / "build.json").write_text(json.dumps(build, indent=1))- print(f"[wrapper] done ok={build['ok']} in {build['duration_ms']} ms")-- try:- links = _urdf_links(urdf)- except ET.ParseError as e:- build.update(error_type="UrdfParseError", error_message=str(e), error_file="src/robot.urdf")- finish()- return- bad = _bad_links(links)- if bad:- build.update(error_type="UnsafeLinkName", error_file="src/robot.urdf",- error_message="URDF link name(s) unusable as meshes/<link>.glb filenames "- "(must match [A-Za-z][A-Za-z0-9_]*): "- + ", ".join(repr(b) for b in bad))- finish()- return-- bpy.ops.wm.read_factory_settings(use_empty=True)- err = _exec_script(script)- build["stdout_tail"] = err.pop("script_stdout", "")- if err:- build.update(error_type=err["error_type"], error_message=err["error_message"], error_line=err["error_line"],- stderr_tail=err["traceback"])- finish()- return-- depsgraph = bpy.context.evaluated_depsgraph_get()- census["objects"] = _census(depsgraph)- by_name = {ob.name: ob for ob in bpy.data.objects if ob.type in MESH_LIKE or ob.type == "EMPTY"}- claimed: set[str] = set()- for link in links:- ob = by_name.get(link)- if ob is None:- census["missing_links"].append(link)- near = [o.name for o in bpy.data.objects if o.type in MESH_LIKE and _snake(o.name) == _snake(link)]- if near:- census["hints"][link] = f"no object named exactly '{link}' — did you mean {near}? names are case-sensitive"- continue- group = [ob] + _descendants(ob)- group = [o for o in group if o.type in MESH_LIKE]- if not group:- census["missing_links"].append(link)- census["hints"][link] = f"object '{link}' has no mesh geometry (type {ob.type})"- continue- claimed.update(o.name for o in group)- try:- census["links"][link] = _export_link(link, group, out / "meshes" / f"{link}.glb", depsgraph)- except Exception as e: # export failure is a build failure- build.update(error_type="ExportError", error_message=f"link {link}: {e}", error_file="src/model.py")- finish()- return- census["unmatched_objects"] = [r["name"] for r in census["objects"] if r["name"] not in claimed]- if census["missing_links"]:- build.update(error_type="MissingLinkObjects", error_file="src/model.py",- error_message="URDF links without a mesh object in model.py: " + ", ".join(census["missing_links"]))- finish()- return- if census["unmatched_objects"]:- build.update(error_type="UnmatchedObjects", error_file="src/model.py",- error_message="mesh objects that are not URDF links (parent them under a link object or add a <link>): "- + ", ".join(census["unmatched_objects"]))- finish()- return- build["ok"] = True- build["extra_paths"] = {"meshes_dir": str(out / "meshes")}- finish()---main()diff --git a/harness/codeverse3d/languages/blender/wrappers/_census.py b/harness/codeverse3d/languages/wrappers/_census.pysimilarity index 94%rename from harness/codeverse3d/languages/blender/wrappers/_census.pyrename to harness/codeverse3d/languages/wrappers/_census.pyindex 748850f3..3805620f 100644--- a/harness/codeverse3d/languages/blender/wrappers/_census.py+++ b/harness/codeverse3d/languages/wrappers/_census.py@@ -1,10 +1,10 @@-"""Scene census for the Blender build wrapper — executed BY Blender, never imported by the harness.+"""Scene census for the Blender build wrappers — executed BY Blender, never imported by the harness.-``run_bpy.py`` puts its own directory on ``sys.path`` and does ``import _census``; this-module must therefore stay standalone (no ``codeverse3d`` imports). It inspects the scene-after the agent script ran: evaluated triangle counts, world bboxes, materials, parents,-and the contract warnings the build cannot otherwise see (cameras, lights, visible-boolean cutters, unlinked meshes, default primitive names, material slots no polygon uses).+``run_bpy.py`` and ``run_bpy_links.py`` import it as a sibling module; it must therefore+stay standalone (no ``codeverse3d`` imports). It inspects the scene after the agent+script ran: evaluated triangle counts, world bboxes, materials, parents, and the contract+warnings the build cannot otherwise see (cameras, lights, visible boolean cutters,+unlinked meshes, default primitive names, material slots no polygon uses)."""from __future__ import annotationsdiff --git a/harness/codeverse3d/languages/wrappers/_wrapper_common.py b/harness/codeverse3d/languages/wrappers/_wrapper_common.pynew file mode 100644index 00000000..43aa779e--- /dev/null+++ b/harness/codeverse3d/languages/wrappers/_wrapper_common.py@@ -0,0 +1,160 @@+"""What every python build wrapper does around the agent's script — run_bpy.py and+run_bpy_links.py inside Blender (its bundled python 3.11), run_cq.py in the harness python.++Standalone: stdlib only and no 3.12+ syntax, never imported by the harness. A wrapper puts+its own directory on ``sys.path`` and imports this module as a sibling; ``run_script`` takes+that directory off again before the agent's code runs.++The report a wrapper writes is ``build.json`` — the runtime reads it once and replaces it+with the final ``BuildResult`` (``languages/_common.compose_build_result``).+"""++from __future__ import annotations++import importlib+import json+import os+import random+import runpy+import sys+import time+import traceback+from collections.abc import Callable+from typing import Any++WRAPPER_DIR = os.path.dirname(os.path.realpath(__file__))+PARTS_PKG = "parts" # src/parts/<snake>.py → ``from parts.<snake> import build_<snake>``+++def wrapper_argv() -> list[str]:+ """The wrapper's own arguments: after ``--`` under Blender, else ``sys.argv[1:]``."""+ return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]+++def new_report(language: str, rlimit_gb: float, **extra: Any) -> dict[str, Any]:+ """The build.json skeleton; applies the memory cap (RLIMIT_AS, so a geometry bomb dies+ in-process) and says whether it took."""+ return {"ok": False, "language": language, "error_type": "", "error_message": "", "error_file": "",+ "error_line": None, "error_source": "", "traceback": "", "warnings": [], "exported": {},+ "rlimit": _apply_rlimit(rlimit_gb), **extra}+++def _apply_rlimit(gb: float) -> str:+ if gb <= 0:+ return "rlimit disabled"+ try:+ import resource++ cap = int(gb * 1024**3)+ _soft, hard = resource.getrlimit(resource.RLIMIT_AS)+ lim = cap if hard == resource.RLIM_INFINITY else min(cap, hard)+ resource.setrlimit(resource.RLIMIT_AS, (lim, hard))+ return f"RLIMIT_AS={lim // 1024**2} MB"+ except (ImportError, ValueError, OSError) as e:+ return f"rlimit not applied: {e}"+++def seed_everything(seed: int) -> None:+ """``random``, numpy and ``mathutils.noise`` (whichever this interpreter has)."""+ random.seed(seed)+ try:+ import numpy as np++ np.random.seed(seed)+ except ImportError:+ pass+ try:+ from mathutils import noise++ noise.seed_set(seed)+ except (ImportError, AttributeError):+ pass+++def src_relative(path: str, src_dir: str) -> str | None:+ """``/ws/src/parts/leg.py`` → ``src/parts/leg.py`` when ``path`` lives under ``src_dir``; else None.++ Every runtime reports ``error_file`` workspace-relative so the repair loop can open it."""+ real_src = os.path.realpath(src_dir)+ real = os.path.realpath(path)+ if real == real_src or not real.startswith(real_src + os.sep):+ return None+ return os.path.join(os.path.basename(real_src), os.path.relpath(real, real_src)).replace(os.sep, "/")+++def map_exception(exc: BaseException, script_path: str, *, hint: str = "", memory: str = "") -> dict[str, Any]:+ """Traceback → {error_type, error_message, error_file, error_line, error_source, traceback}.++ The innermost frame under ``src/`` wins, so a failure in a part or helper file is+ reported against that file, not the ``model.py`` line that called it. ``hint`` is+ appended to the message; ``memory`` replaces it on a MemoryError (what to reduce)."""+ src_dir = os.path.dirname(os.path.abspath(script_path))+ info: dict[str, Any] = {"error_type": type(exc).__name__, "error_message": (str(exc) or type(exc).__name__) + hint,+ "error_file": "", "error_line": None, "error_source": ""}+ syntax_rel = src_relative(exc.filename, src_dir) if isinstance(exc, SyntaxError) and exc.filename else None+ if syntax_rel:+ info.update(error_file=syntax_rel, error_line=exc.lineno, error_source=(exc.text or "").strip())+ else:+ for frame in reversed(traceback.extract_tb(exc.__traceback__)):+ rel = src_relative(frame.filename, src_dir)+ if rel:+ info.update(error_file=rel, error_line=frame.lineno, error_source=(frame.line or "").strip())+ break+ if isinstance(exc, MemoryError):+ info["error_message"] = f"MemoryError: the script hit the memory cap — {memory or 'reduce it'}"+ info["traceback"] = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))[-6000:]+ return info+++def run_script(script_path: str) -> tuple[BaseException | None, dict[str, Any] | None]:+ """Execute the agent's entry script as ``__main__`` → (what it raised, its globals).++ ``<ws>/src`` goes first on ``sys.path`` (``from parts.leg import build_leg``, a helper+ module beside model.py); the wrapper's own directory goes off it, no bytecode is+ written into the git-tracked src/. ``sys.exit(0)`` is not a failure: it returns+ ``(None, None)`` — no globals to read."""+ src_dir = os.path.dirname(os.path.abspath(script_path))+ sys.path[:] = [p for p in sys.path if os.path.realpath(p) not in (os.path.realpath(src_dir), WRAPPER_DIR)]+ sys.path.insert(0, src_dir)+ sys.dont_write_bytecode = True+ for name in [m for m in sys.modules if m == PARTS_PKG or m.startswith(PARTS_PKG + ".")]:+ del sys.modules[name] # never reuse a stale module from somewhere else on the path+ importlib.invalidate_caches()+ saved_argv = sys.argv+ sys.argv = [script_path]+ try:+ return None, runpy.run_path(script_path, run_name="__main__")+ except SystemExit as e:+ return (None, None) if e.code in (None, 0) else (e, None)+ except BaseException as e: # noqa: BLE001 — every failure must be reported, never propagate+ return e, None+ finally:+ sys.argv = saved_argv+++def write_report(out_dir: str, report: dict[str, Any], census: dict[str, Any], t0: float) -> None:+ """census.json + build.json, atomically; a failure's traceback also goes to stderr, where+ the runtime's ``stderr_tail`` (and so the repair prompt) picks it up."""+ report["duration_ms"] = int((time.monotonic() - t0) * 1000)+ _write_json_atomic(os.path.join(out_dir, "census.json"), census)+ _write_json_atomic(os.path.join(out_dir, "build.json"), report)+ if report.get("traceback"):+ print(report["traceback"], file=sys.stderr, end="")+++def _write_json_atomic(path: str, data: Any) -> None:+ tmp = path + ".tmp"+ with open(tmp, "w", encoding="utf-8") as fh:+ json.dump(data, fh, indent=2, default=str)+ os.replace(tmp, path)+++def exit_after(main: Callable[[], int]) -> None:+ """``sys.exit(main())``: 0 once the report is written (even when the script failed),+ 2 on a wrapper bug — traceback on stderr, no report."""+ try:+ code = main()+ except Exception: # noqa: BLE001+ traceback.print_exc()+ code = 2+ sys.exit(code)diff --git a/harness/codeverse3d/languages/blender/wrappers/run_bpy.py b/harness/codeverse3d/languages/wrappers/run_bpy.pysimilarity index 55%rename from harness/codeverse3d/languages/blender/wrappers/run_bpy.pyrename to harness/codeverse3d/languages/wrappers/run_bpy.pyindex 7679bae6..d957c79a 100644--- a/harness/codeverse3d/languages/blender/wrappers/run_bpy.py+++ b/harness/codeverse3d/languages/wrappers/run_bpy.py@@ -8,47 +8,50 @@ What it does (in order):1. caps the address space (RLIMIT_AS) so geometry bombs die in-process;2. empties the factory scene (Cube/Camera/Light + orphan data), sets metric units;3. seeds ``random`` / numpy / mathutils.noise;- 4. puts ``<ws>/src`` on ``sys.path`` (so ``from parts.seat import build_seat`` and- ``import parts.seat`` work), runs the agent's ``model.py`` with ``runpy`` and maps- any exception to ``<file under src/>:<line>`` (model.py or a part file);- 5. collects a census (``_census.py`` next to this file: evaluated tri counts, world- bboxes, materials, parents);+ 4. runs the agent's ``model.py`` with ``<ws>/src`` on ``sys.path`` (so ``from+ parts.seat import build_seat`` and ``import parts.seat`` work) and maps any+ exception to ``<file under src/>:<line>`` (model.py or a part file);+ 5. collects a census (``_census.py``: evaluated tri counts, world bboxes, materials, parents);6. warns on leftovers (cameras, lights, touched render settings, visible cutters);7. exports ``object.glb`` (Y-up, +Z front) and optionally ``object.stl`` (Z-up);8. writes ``build.json`` + ``census.json`` atomically and exits 0.Exit codes: 0 = reported (even if the script failed); 2 = wrapper bug (no report).-This file must stay standalone: Blender's python cannot import ``codeverse3d``-(the only sibling import is ``_census``, resolved via this file's own directory).+Standalone: Blender's python cannot import ``codeverse3d``; the sibling modules+(``_wrapper_common``, ``_census``) are imported from this file's own directory."""from __future__ import annotationsimport argparseimport contextlib-import importlib-import jsonimport os-import random-import runpyimport sysimport timeimport tracebackfrom typing import Any-_WRAPPER_DIR = os.path.dirname(os.path.abspath(__file__))-if _WRAPPER_DIR not in sys.path:- sys.path.insert(0, _WRAPPER_DIR)-from _census import collect_census, is_hidden # noqa: E402 (sibling module, Blender-executed)+sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))+from _census import collect_census, is_hidden # noqa: E402 (siblings, Blender-executed)+from _wrapper_common import ( # noqa: E402+ PARTS_PKG,+ exit_after,+ map_exception,+ new_report,+ run_script,+ seed_everything,+ wrapper_argv,+ write_report,+)GLB_NAME = "object.glb"STL_NAME = "object.stl"BLEND_NAME = "object.blend"EXPORT_TYPES = {"MESH", "CURVE", "SURFACE", "FONT", "META", "EMPTY"}-PARTS_PKG = "parts" # src/parts/<snake>.py → ``from parts.<snake> import build_<snake>``+MEMORY_HINT = ("a geometry bomb (tiny remesh voxel_size, huge subdivision/array counts, nested loops "+ "creating millions of faces). Reduce it.")-# ----------------------------------------------------------------------------- args / iodef parse_args(argv: list[str]) -> argparse.Namespace:p = argparse.ArgumentParser(prog="run_bpy.py")p.add_argument("--script", required=True)@@ -61,29 +64,6 @@ def parse_args(argv: list[str]) -> argparse.Namespace:return p.parse_args(argv)-def write_json_atomic(path: str, data: Any) -> None:- tmp = path + ".tmp"- with open(tmp, "w", encoding="utf-8") as fh:- json.dump(data, fh, indent=2, default=str)- os.replace(tmp, path)---def apply_rlimit(gb: float) -> str:- """Cap virtual memory; returns a note for build.json."""- if gb <= 0:- return "rlimit disabled"- try:- import resource-- cap = int(gb * 1024**3)- _soft, hard = resource.getrlimit(resource.RLIMIT_AS)- lim = cap if hard == resource.RLIM_INFINITY else min(cap, hard)- resource.setrlimit(resource.RLIMIT_AS, (lim, hard))- return f"RLIMIT_AS={lim // 1024**2} MB"- except (ImportError, ValueError, OSError) as e:- return f"rlimit not applied: {e}"--# ----------------------------------------------------------------------------- scene prepdef clear_scene(bpy: Any) -> None:"""Remove every object + datablock of the factory scene; keep scene/world."""@@ -105,22 +85,6 @@ def clear_scene(bpy: Any) -> None:scene.unit_settings.length_unit = "METERS"-def seed_everything(seed: int) -> None:- random.seed(seed)- try:- import numpy as np-- np.random.seed(seed)- except ImportError:- pass- try:- from mathutils import noise-- noise.seed_set(seed)- except (ImportError, AttributeError):- pass--def render_fingerprint(bpy: Any) -> dict[str, Any]:r = bpy.context.scene.renderreturn {@@ -131,16 +95,7 @@ def render_fingerprint(bpy: Any) -> dict[str, Any]:}-# ----------------------------------------------------------------------------- exec + error mapping-def src_relative(path: str, src_dir: str) -> str | None:- """``/ws/src/parts/leg.py`` → ``src/parts/leg.py`` when ``path`` lives under ``src_dir``; else None."""- real_src = os.path.realpath(src_dir)- real = os.path.realpath(path)- if real == real_src or not real.startswith(real_src + os.sep):- return None- return os.path.join(os.path.basename(real_src), os.path.relpath(real, real_src)).replace(os.sep, "/")--+# ----------------------------------------------------------------------------- errorsdef import_hint(exc: BaseException, src_dir: str) -> str:"""Extra guidance for the two import mistakes a multi-file model makes."""msg = str(exc)@@ -154,68 +109,8 @@ def import_hint(exc: BaseException, src_dir: str) -> str:return ""-def map_exception(exc: BaseException, script_path: str) -> dict[str, Any]:- """Traceback → {error_type, error_message, error_file, error_line, error_source, traceback}.-- ``error_file`` is workspace-relative (``src/model.py``, ``src/parts/leg.py``): the- innermost traceback frame inside ``src/`` wins, so a failure in a part file is- reported against that file, not against the ``from parts.x import …`` line.- """- src_dir = os.path.dirname(os.path.abspath(script_path))- info: dict[str, Any] = {- "error_type": type(exc).__name__,- "error_message": (str(exc) or type(exc).__name__) + import_hint(exc, src_dir),- "error_file": "",- "error_line": None,- "error_source": "",- }- syntax_rel = src_relative(exc.filename, src_dir) if isinstance(exc, SyntaxError) and exc.filename else None- if syntax_rel:- info.update(error_file=syntax_rel, error_line=exc.lineno, error_source=(exc.text or "").strip())- else:- for frame in reversed(traceback.extract_tb(exc.__traceback__)):- rel = src_relative(frame.filename, src_dir)- if rel:- info.update(error_file=rel, error_line=frame.lineno, error_source=(frame.line or "").strip())- break- if isinstance(exc, MemoryError):- info["error_message"] = (- "MemoryError: the script hit the memory cap — a geometry bomb (tiny remesh voxel_size, "- "huge subdivision/array counts, nested loops creating millions of faces). Reduce it."- )- tb = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))- info["traceback"] = tb[-6000:]- return info---def run_script(script_path: str) -> dict[str, Any] | None:- """Execute the agent's entry script as ``__main__``; return error info or None.-- ``<ws>/src`` goes first on ``sys.path`` so the entry can import its part modules- (``src/parts/<snake>.py``) either way: ``from parts.leg import build_leg`` or- ``import parts.leg``. A single-file ``model.py`` keeps working unchanged.- """- src_dir = os.path.dirname(os.path.abspath(script_path))- if _WRAPPER_DIR in sys.path: # the agent's code must not see the wrapper's helpers- sys.path.remove(_WRAPPER_DIR)- sys.path[:] = [p for p in sys.path if os.path.realpath(p) != os.path.realpath(src_dir)]- sys.path.insert(0, src_dir)- sys.dont_write_bytecode = True # no __pycache__ inside the agent's git-tracked src/- for name in [m for m in sys.modules if m == PARTS_PKG or m.startswith(PARTS_PKG + ".")]:- del sys.modules[name] # never reuse a stale module from somewhere else on the path- importlib.invalidate_caches()- saved_argv = sys.argv- sys.argv = [script_path]- try:- runpy.run_path(script_path, run_name="__main__")- except SystemExit as e: # sys.exit(0) in a script is not a failure- if e.code not in (None, 0):- return map_exception(e, script_path)- except BaseException as e: # noqa: BLE001 — every failure must be reported, never propagate- return map_exception(e, script_path)- finally:- sys.argv = saved_argv- return None+def script_error(exc: BaseException, script: str) -> dict[str, Any]:+ return map_exception(exc, script, hint=import_hint(exc, os.path.dirname(script)), memory=MEMORY_HINT)# ----------------------------------------------------------------------------- export@@ -265,28 +160,17 @@ def export_stl(bpy: Any, path: str) -> None:# ----------------------------------------------------------------------------- maindef main() -> int:- argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []- args = parse_args(argv)+ args = parse_args(wrapper_argv())import bpy # noqa: PLC0415 — only available inside Blenderout_dir = os.path.abspath(args.out)os.makedirs(out_dir, exist_ok=True)script = os.path.abspath(args.script)- build_path = os.path.join(out_dir, "build.json")- census_path = os.path.join(out_dir, "census.json")- for stale in (build_path, census_path, os.path.join(out_dir, GLB_NAME), os.path.join(out_dir, STL_NAME)):- if os.path.exists(stale):- os.remove(stale)-t0 = time.monotonic()- report: dict[str, Any] = {- "ok": False, "language": "blender", "error_type": "", "error_message": "", "error_file": "",- "error_line": None, "error_source": "", "traceback": "", "warnings": [], "exported": {},- "blender_version": bpy.app.version_string, "rlimit": apply_rlimit(args.rlimit_gb),- }+ report = new_report("blender", args.rlimit_gb, blender_version=bpy.app.version_string)if not os.path.isfile(script):report.update(error_type="FileNotFoundError", error_message=f"script not found: {script}")- write_json_atomic(build_path, report)+ write_report(out_dir, report, {}, t0)return 0clear_scene(bpy)@@ -294,10 +178,10 @@ def main() -> int:render_before = render_fingerprint(bpy)t_exec = time.monotonic()- err = run_script(script)+ exc, _ = run_script(script)report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)- if err:- report.update(err)+ if exc is not None:+ report.update(script_error(exc, script))# the script may have left edit mode / odd selection states behindtry:@@ -310,9 +194,8 @@ def main() -> int:if render_fingerprint(bpy) != render_before:census["warnings"].append("script changed render settings (engine/resolution/filepath/frames): remove that code")report["warnings"] = census["warnings"]- write_json_atomic(census_path, census)- if not err and census["tri_count"] > args.tri_limit:+ if exc is None and census["tri_count"] > args.tri_limit:report.update(error_type="TriangleBudgetExceeded",error_message=f"{census['tri_count']} triangles > limit {args.tri_limit}; lower subdivision levels / segment counts",@@ -347,15 +230,9 @@ def main() -> int:report.update(error_type="EmptyScene", error_message="the script created no visible mesh objects")report["ok"] = not report["error_type"] and "glb" in report["exported"]- report["duration_ms"] = int((time.monotonic() - t0) * 1000)- write_json_atomic(build_path, report)+ write_report(out_dir, report, census, t0)return 0if __name__ == "__main__":- try:- code = main()- except Exception: # wrapper bug: no report, loud exit- traceback.print_exc()- code = 2- sys.exit(code)+ exit_after(main)diff --git a/harness/codeverse3d/languages/wrappers/run_bpy_links.py b/harness/codeverse3d/languages/wrappers/run_bpy_links.pynew file mode 100644index 00000000..1d3a2402--- /dev/null+++ b/harness/codeverse3d/languages/wrappers/run_bpy_links.py@@ -0,0 +1,184 @@+"""Blender-side build wrapper for the ``urdf_blender`` language (run BY THE HARNESS).++ blender -b --factory-startup --python run_bpy_links.py -- \+ --script src/model.py --urdf src/robot.urdf --out artifacts/ [--rlimit-gb 12] [--seed 0]++1. empties the scene, seeds, executes ``model.py`` (``_wrapper_common``: errors mapped to+ their ``src/`` file and line, ``sys.exit(0)`` is not a failure — as for the blender language),+2. takes the blender language's census of the scene (``_census.collect_census``),+3. matches URDF link names to objects (an object named exactly ``<link>`` plus+ anything parented under it forms that link's mesh),+4. exports ``<out>/meshes/<link>.glb`` per link with the geometry baked in WORLD+ coordinates at the authored rest pose, Z-up (``export_yup=False`` — the file+ holds URDF-frame coordinates, NOT glTF Y-up), then+5. writes ``<out>/census.json`` and ``<out>/build.json``.++Self-contained on purpose: Blender's bundled python cannot import ``codeverse3d``; the+sibling modules are imported from this file's own directory.+"""++import argparse+import os+import re+import sys+import time+import xml.etree.ElementTree as ET+from pathlib import Path++import bpy+from mathutils import Matrix, Vector++sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))+from _census import collect_census, world_bbox # noqa: E402 (siblings, Blender-executed)+from _wrapper_common import ( # noqa: E402+ exit_after,+ map_exception,+ new_report,+ run_script,+ seed_everything,+ wrapper_argv,+ write_report,+)++MESH_LIKE = {"MESH", "CURVE", "FONT", "SURFACE", "META"}+TRI_LIMIT = 600_000 # a warning here (census), the blender language's build error+++def _snake(name: str) -> str:+ s = re.sub(r"[^0-9A-Za-z]+", "_", name.strip())+ s = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", s)+ return re.sub(r"_+", "_", s).strip("_").lower()+++#: link names double as ``meshes/<link>.glb`` filename stems: plain identifiers only.+#: The lint layer states the same rule (``languages/urdf/lint._IDENT``) but only WARNs,+#: so the wrapper enforces it — ``../evil`` must be a build error, never a file written+#: outside ``meshes/``.+_SAFE_LINK = re.compile(r"[A-Za-z][A-Za-z0-9_]*")+++def _bad_links(links: list[str]) -> list[str]:+ """Link names that are unsafe as filenames (not plain identifiers)."""+ return [name for name in links if not _SAFE_LINK.fullmatch(name or "")]+++def _urdf_links(urdf_path: Path) -> list[str]:+ root = ET.parse(urdf_path).getroot()+ return [el.get("name", "") for el in root.findall("link")]+++def _evaluated_world_mesh(ob, depsgraph):+ """New bpy Mesh datablock of ``ob`` (modifiers applied) in WORLD coordinates."""+ ev = ob.evaluated_get(depsgraph)+ me = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph)+ me.transform(ob.matrix_world)+ return me+++def _export_link(link: str, objects: list, out_glb: Path, depsgraph) -> dict:+ """Join ``objects`` (world space) into one temp object and export it as GLB."""+ meshes = [_evaluated_world_mesh(ob, depsgraph) for ob in objects]+ temp_objs = []+ for i, me in enumerate(meshes):+ o = bpy.data.objects.new(f"__c3v_{link}_{i}", me)+ bpy.context.scene.collection.objects.link(o)+ temp_objs.append(o)+ bpy.ops.object.select_all(action="DESELECT")+ for o in temp_objs:+ o.select_set(True)+ bpy.context.view_layer.objects.active = temp_objs[0]+ if len(temp_objs) > 1:+ bpy.ops.object.join()+ joined = bpy.context.view_layer.objects.active+ joined.name = link+ joined.matrix_world = Matrix.Identity(4)+ bpy.ops.object.select_all(action="DESELECT")+ joined.select_set(True)+ joined.data.calc_loop_triangles()+ lo, hi = world_bbox(joined, Vector)+ info = {+ "mesh": f"meshes/{link}.glb", "tris": len(joined.data.loop_triangles), "verts": len(joined.data.vertices),+ "bbox_min": lo, "bbox_max": hi, "objects": [o.name for o in objects],+ }+ out_glb.parent.mkdir(parents=True, exist_ok=True)+ bpy.ops.export_scene.gltf(+ filepath=str(out_glb), export_format="GLB", use_selection=True, export_yup=False, export_apply=True,+ export_materials="EXPORT", export_extras=False, export_animations=False, export_cameras=False,+ export_lights=False, export_normals=True, export_texcoords=True, export_skins=False, export_morph=False,+ )+ bpy.data.objects.remove(joined, do_unlink=True)+ return info+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--script", required=True)+ ap.add_argument("--urdf", required=True)+ ap.add_argument("--out", required=True)+ ap.add_argument("--rlimit-gb", type=float, default=12.0)+ ap.add_argument("--seed", type=int, default=0)+ args = ap.parse_args(wrapper_argv())+ t0 = time.monotonic()+ script, urdf, out = Path(args.script).resolve(), Path(args.urdf).resolve(), Path(args.out).resolve()+ out.mkdir(parents=True, exist_ok=True)+ report = new_report("urdf_blender", args.rlimit_gb, error_file="src/model.py")+ census: dict = {"objects": [], "links": {}, "unmatched_objects": [], "missing_links": [], "hints": {}}++ def fail(error_type: str, message: str, error_file: str = "src/model.py") -> int:+ report.update(error_type=error_type, error_message=message, error_file=error_file)+ write_report(str(out), report, census, t0)+ return 0++ try:+ links = _urdf_links(urdf)+ except ET.ParseError as e:+ return fail("UrdfParseError", str(e), "src/robot.urdf")+ bad = _bad_links(links)+ if bad:+ return fail("UnsafeLinkName", "URDF link name(s) unusable as meshes/<link>.glb filenames "+ "(must match [A-Za-z][A-Za-z0-9_]*): " + ", ".join(repr(b) for b in bad), "src/robot.urdf")++ bpy.ops.wm.read_factory_settings(use_empty=True)+ seed_everything(args.seed)+ exc, _ = run_script(str(script))+ if exc is not None:+ report.update(map_exception(exc, str(script)))+ write_report(str(out), report, census, t0)+ return 0++ census.update(collect_census(bpy, TRI_LIMIT))+ depsgraph = bpy.context.evaluated_depsgraph_get()+ by_name = {ob.name: ob for ob in bpy.data.objects if ob.type in MESH_LIKE or ob.type == "EMPTY"}+ claimed: set[str] = set()+ for link in links:+ ob = by_name.get(link)+ if ob is None:+ census["missing_links"].append(link)+ near = [o.name for o in bpy.data.objects if o.type in MESH_LIKE and _snake(o.name) == _snake(link)]+ if near:+ census["hints"][link] = f"no object named exactly '{link}' — did you mean {near}? names are case-sensitive"+ continue+ group = [o for o in (ob, *ob.children_recursive) if o.type in MESH_LIKE]+ if not group:+ census["missing_links"].append(link)+ census["hints"][link] = f"object '{link}' has no mesh geometry (type {ob.type})"+ continue+ claimed.update(o.name for o in group)+ try:+ census["links"][link] = _export_link(link, group, out / "meshes" / f"{link}.glb", depsgraph)+ except Exception as e: # export failure is a build failure+ return fail("ExportError", f"link {link}: {e}")+ census["unmatched_objects"] = [o["name"] for o in census["objects"]+ if o["type"] in MESH_LIKE and o["name"] not in claimed]+ if census["missing_links"]:+ return fail("MissingLinkObjects",+ "URDF links without a mesh object in model.py: " + ", ".join(census["missing_links"]))+ if census["unmatched_objects"]:+ return fail("UnmatchedObjects", "mesh objects that are not URDF links (parent them under a link object or add "+ "a <link>): " + ", ".join(census["unmatched_objects"]))+ report["ok"] = True+ write_report(str(out), report, census, t0)+ return 0+++exit_after(main)diff --git a/harness/codeverse3d/languages/cadquery/wrappers/run_cq.py b/harness/codeverse3d/languages/wrappers/run_cq.pysimilarity index 64%rename from harness/codeverse3d/languages/cadquery/wrappers/run_cq.pyrename to harness/codeverse3d/languages/wrappers/run_cq.pyindex 6e9cbcb5..ab763149 100644--- a/harness/codeverse3d/languages/cadquery/wrappers/run_cq.py+++ b/harness/codeverse3d/languages/wrappers/run_cq.py@@ -3,30 +3,40 @@python run_cq.py --script /abs/src/model.py --out /abs/artifacts \[--rlimit-gb 8] [--tri-limit 600000] [--tolerance 0.001] [--angular-tolerance 0.15] [--seed 0]-Steps: RLIMIT_AS → exec model.py (runpy) with traceback→line mapping → read the-module-level ``result`` (cq.Assembly preferred, or Workplane / Shape) → tessellate-each part (world location applied) → ``object.glb`` (Y-up, +Z front, named nodes,-PBR base colour from cq.Color) + ``object.step`` + ``object.stl`` → ``census.json``-+ ``build.json`` (atomic). Exit 0 whenever a report was written; 2 on wrapper bugs.-Standalone: imports cadquery / numpy / trimesh only (never ``codeverse3d``).+Steps: RLIMIT_AS → seed → exec model.py with traceback→line mapping (``_wrapper_common``,+shared with the Blender wrappers) → read the module-level ``result`` (cq.Assembly+preferred, or Workplane / Shape) → tessellate each part (world location applied) →+``object.glb`` (Y-up, +Z front, named nodes, PBR base colour from cq.Color) ++``object.step`` + ``object.stl`` → ``census.json`` + ``build.json`` (atomic). Exit 0+whenever a report was written; 2 on wrapper bugs. Standalone: imports cadquery / numpy /+trimesh and its sibling ``_wrapper_common`` only (never ``codeverse3d``)."""from __future__ import annotationsimport argparse-import jsonimport os-import randomimport re-import runpyimport sysimport time-import tracebackfrom typing import Any+sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))+from _wrapper_common import ( # noqa: E402 (sibling module)+ exit_after,+ map_exception,+ new_report,+ run_script,+ seed_everything,+ src_relative,+ wrapper_argv,+ write_report,+)+GLB_NAME, STEP_NAME, STL_NAME = "object.glb", "object.step", "object.stl"PASCAL_RE = re.compile(r"^[A-Z][A-Za-z0-9]*(?:_\d+)?$")DEFAULT_RGBA = (0.7, 0.7, 0.7, 1.0)+MEMORY_HINT = "reduce boolean/pattern counts or tessellation density."def parse_args(argv: list[str]) -> argparse.Namespace:@@ -41,94 +51,22 @@ def parse_args(argv: list[str]) -> argparse.Namespace:return p.parse_args(argv)-def write_json_atomic(path: str, data: Any) -> None:- tmp = path + ".tmp"- with open(tmp, "w", encoding="utf-8") as fh:- json.dump(data, fh, indent=2, default=str)- os.replace(tmp, path)---def apply_rlimit(gb: float) -> str:- if gb <= 0:- return "rlimit disabled"- try:- import resource-- cap = int(gb * 1024**3)- _soft, hard = resource.getrlimit(resource.RLIMIT_AS)- lim = cap if hard == resource.RLIM_INFINITY else min(cap, hard)- resource.setrlimit(resource.RLIMIT_AS, (lim, hard))- return f"RLIMIT_AS={lim // 1024**2} MB"- except (ImportError, ValueError, OSError) as e:- return f"rlimit not applied: {e}"---# ----------------------------------------------------------------------------- exec + errors-def src_relative(path: str, src_dir: str) -> str | None:- """``/ws/src/helpers.py`` → ``src/helpers.py`` when ``path`` lives under ``src_dir``; else None.-- Every runtime reports ``error_file`` workspace-relative (``src/...``) so the repair- loop can open the file; the bare basename would resolve to ``<ws>/model.py``.- """- real_src = os.path.realpath(src_dir)- real = os.path.realpath(path)- if real == real_src or not real.startswith(real_src + os.sep):- return None- return os.path.join(os.path.basename(real_src), os.path.relpath(real, real_src)).replace(os.sep, "/")--def entry_relative(script_path: str) -> str:"""``src/model.py`` for the entry script itself."""return src_relative(script_path, os.path.dirname(os.path.abspath(script_path))) or os.path.basename(script_path)-def map_exception(exc: BaseException, script_path: str) -> dict[str, Any]:- """Traceback → {error_type, error_message, error_file, error_line, error_source, traceback}.+def occ_hint(exc: BaseException) -> str:+ """What an OCC kernel refusal usually means, appended to its message."""+ if "BRep_API: command not done" in str(exc) or "StdFail_NotDone" in type(exc).__name__:+ return (" — OCC kernel refused the operation: fillet/chamfer radius >= adjacent wall/face size, conflicting "+ "adjacent fillets, or degenerate geometry. Clamp radii (< 0.45 x min thickness), select fewer edges, "+ "fillet before booleans.")+ return ""- The innermost frame under ``src/`` wins, so an exception raised in a helper module- (``src/helpers.py``) is reported against that file, not the ``model.py`` call site.- """- src_dir = os.path.dirname(os.path.abspath(script_path))- info: dict[str, Any] = {"error_type": type(exc).__name__, "error_message": str(exc) or type(exc).__name__,- "error_file": "", "error_line": None, "error_source": ""}- syntax_rel = src_relative(exc.filename, src_dir) if isinstance(exc, SyntaxError) and exc.filename else None- if syntax_rel:- info.update(error_file=syntax_rel, error_line=exc.lineno, error_source=(exc.text or "").strip())- else:- for fr in reversed(traceback.extract_tb(exc.__traceback__)):- rel = src_relative(fr.filename, src_dir)- if rel:- info.update(error_file=rel, error_line=fr.lineno, error_source=(fr.line or "").strip())- break- msg = info["error_message"]- if "BRep_API: command not done" in msg or "StdFail_NotDone" in info["error_type"]:- info["error_message"] = msg + (- " — OCC kernel refused the operation: fillet/chamfer radius >= adjacent wall/face size, conflicting adjacent "- "fillets, or degenerate geometry. Clamp radii (< 0.45 x min thickness), select fewer edges, fillet before booleans.")- if isinstance(exc, MemoryError):- info["error_message"] = "MemoryError: memory cap hit — reduce boolean/pattern counts or tessellation density."- info["traceback"] = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))[-6000:]- return info---def run_script(script_path: str) -> tuple[dict[str, Any] | None, dict[str, Any]]:- script_dir = os.path.dirname(os.path.abspath(script_path))- if script_dir not in sys.path:- sys.path.insert(0, script_dir)- saved = sys.argv- sys.argv = [script_path]- try:- ns = runpy.run_path(script_path, run_name="__main__")- return None, ns- except SystemExit as e:- if e.code in (None, 0):- return {"error_type": "SystemExit", "error_message": "script called sys.exit() before `result` could be read; remove it",- "error_file": entry_relative(script_path), "error_line": None, "error_source": "", "traceback": ""}, {}- return map_exception(e, script_path), {}- except BaseException as e: # noqa: BLE001- return map_exception(e, script_path), {}- finally:- sys.argv = saved++def script_error(exc: BaseException, script: str) -> dict[str, Any]:+ return map_exception(exc, script, hint=occ_hint(exc), memory=MEMORY_HINT)# ----------------------------------------------------------------------------- parts@@ -256,33 +194,35 @@ def export_step_stl(cq: Any, result: Any, parts: list[dict[str, Any]], out_dir:# ----------------------------------------------------------------------------- maindef main() -> int:- args = parse_args(sys.argv[1:])+ args = parse_args(wrapper_argv())out_dir = os.path.abspath(args.out)os.makedirs(out_dir, exist_ok=True)- build_path, census_path = os.path.join(out_dir, "build.json"), os.path.join(out_dir, "census.json")- for stale in (build_path, census_path, *(os.path.join(out_dir, n) for n in (GLB_NAME, STEP_NAME, STL_NAME))):- if os.path.exists(stale):- os.remove(stale)t0 = time.monotonic()- report: dict[str, Any] = {"ok": False, "language": "cadquery", "error_type": "", "error_message": "", "error_file": "",- "error_line": None, "error_source": "", "traceback": "", "warnings": [], "exported": {},- "rlimit": apply_rlimit(args.rlimit_gb)}- random.seed(args.seed)+ report = new_report("cadquery", args.rlimit_gb)+ seed_everything(args.seed)import cadquery as cq # noqa: PLC0415 — after the rlimit, before the scriptreport["cadquery_version"] = getattr(cq, "__version__", "?")script = os.path.abspath(args.script)- err, ns = (None, {}) if os.path.isfile(script) else ({"error_type": "FileNotFoundError", "error_message": f"script not found: {script}"}, {})- if err is None:+ err: dict[str, Any] | None = None+ ns: dict[str, Any] | None = {}+ if not os.path.isfile(script):+ err = {"error_type": "FileNotFoundError", "error_message": f"script not found: {script}"}+ else:t_exec = time.monotonic()- err, ns = run_script(script)+ exc, ns = run_script(script)report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)+ if exc is not None:+ err = script_error(exc, script)+ elif ns is None:+ err = {"error_type": "SystemExit", "error_file": entry_relative(script),+ "error_message": "script called sys.exit() before `result` could be read; remove it"}census: dict[str, Any] = {"parts": [], "tri_count": 0, "warnings": report["warnings"], "frame": "z_up_neg_y_front"}- if err is None and "result" not in ns:+ if err is None and ns is not None and "result" not in ns:err = {"error_type": "MissingResult", "error_file": entry_relative(script),"error_message": "model.py must assign a module-level `result` (cq.Assembly or cq.Workplane); ""it must exist at import time, not only under `if __name__ == '__main__':`"}- if err is None:+ if err is None and ns is not None:try:parts, kind = collect_parts(cq, ns["result"], report["warnings"])census["result_kind"] = kind@@ -313,25 +253,16 @@ def main() -> int:report["exported"]["glb"] = glbexport_step_stl(cq, ns["result"], parts, out_dir, args.tolerance, args.angular_tolerance, report)except Exception as e: # noqa: BLE001 — export-time failure in agent geometry- err = map_exception(e, script)+ err = script_error(e, script)if not err["error_file"]:err["error_type"], err["error_message"] = "ExportError", f"{type(e).__name__}: {e}"if err:- report.update({k: v for k, v in err.items() if k in report or k == "traceback"})- if err.get("traceback"):- print(err["traceback"], file=sys.stderr, end="")+ report.update({k: v for k, v in err.items() if k in report})census["n_parts"] = len(census["parts"])- write_json_atomic(census_path, census)report["ok"] = not report["error_type"] and "glb" in report["exported"]- report["duration_ms"] = int((time.monotonic() - t0) * 1000)- write_json_atomic(build_path, report)+ write_report(out_dir, report, census, t0)return 0if __name__ == "__main__":- try:- code = main()- except Exception: # wrapper bug- traceback.print_exc()- code = 2- sys.exit(code)+ exit_after(main)diff --git a/harness/codeverse3d/skills/c3d-blender-forms/SKILL.md b/harness/codeverse3d/skills/c3d-blender-forms/SKILL.mdindex 45e2884e..8ee41ab9 100644--- a/harness/codeverse3d/skills/c3d-blender-forms/SKILL.md+++ b/harness/codeverse3d/skills/c3d-blender-forms/SKILL.md@@ -2,7 +2,7 @@name: c3d-blender-formsdescription: "Use when writing Blender bpy code (language blender or urdf_blender): turn a described shape into the right bpy technique. Avoids the five bpy traps this harness's lint and exporter actually catch: join without an active object, a part file model.py never imports, no PascalCase names, modifier_apply out of context, and primitive_cube_add scale doubling the extents. Covers building, detailing, refining and repairing geometry."license: Apache-2.0-compatibility: Blender 5.0.1 headless, run by codeverse3d/languages/blender/wrappers/run_bpy.py. bpy, bmesh, mathutils, math, random, numpy only.+compatibility: Blender 5.0.1 headless, run by codeverse3d/languages/wrappers/run_bpy.py. bpy, bmesh, mathutils, math, random, numpy only.metadata:evidence: measuredverified: "2026-08-25"diff --git a/harness/codeverse3d/skills/c3d-part-contact/references/contact-recipes.md b/harness/codeverse3d/skills/c3d-part-contact/references/contact-recipes.mdindex 1d55ab52..95133531 100644--- a/harness/codeverse3d/skills/c3d-part-contact/references/contact-recipes.md+++ b/harness/codeverse3d/skills/c3d-part-contact/references/contact-recipes.md@@ -2,7 +2,7 @@Companion to `c3d-part-contact`. Everything here was checked against`codeverse3d/spatial/connectivity.py`, `codeverse3d/spatial/measure.py`, the Blender 5.0.1-wrapper in `codeverse3d/languages/blender/wrappers/run_bpy.py`, and the recorded gate+wrapper in `codeverse3d/languages/wrappers/run_bpy.py`, and the recorded gatefindings under `bench/out/**/artifacts/gates/**` (mined 2026-08-25).## 1. Finding to fixdiff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex 4b8caef4..5a4cf37c 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -114,8 +114,10 @@ codeverse3d/languages/ LanguageRuntime (base.py); one merged module per language since 2026-08-28 —blender/ cadquery/ threejs/ urdf/ scene_threejs/ glsl_shader/ opengl_python/ are eacha single __init__.py (lint → skeleton → runtime, in dependency order) beside their- data (wrappers/, starter/ — Path(__file__) assets unchanged; the contract text- is prompts/<lang>/contract.md, read through RuntimeDocs)+ data (starter/, opengl_python/wrappers/run_gl.py; the contract text is+ prompts/<lang>/contract.md, read through RuntimeDocs); wrappers/ holds the python+ build wrappers (run_bpy, run_bpy_links, run_cq) and what they share+ (_wrapper_common: script run + error mapping + report; _census: the Blender census)spatial/ node.py, render.py, observe.py, tool_common.py (shared tool plumbing),render_scene.py (judge view subset, content-fitted orbit),frame_metrics.py (scene_frames gate), frame_motion.py (measured inter-frame motion),@@ -314,8 +316,8 @@ summary:* **blender** (multi-file): `src/model.py` entry + `src/parts/<snake>.py` eachdefining `def build_<snake>()` (self-contained; optional `src/parts/_x.py`helpers) — pure bpy, Z-up, -Y front, meters; PascalCase object names = part- names. Small objects may stay single-file. Harness wrapper (`run_bpy.py` +- `_census.py`) puts `src/` on sys.path, maps errors to workspace-relative+ names. Small objects may stay single-file. Harness wrapper (`languages/wrappers/run_bpy.py`+ + `_wrapper_common.py` + `_census.py`) puts `src/` on sys.path, maps errors to workspace-relative`src/parts/<x>.py:line`, collects census, exports GLB (Y-up) + STL. The censusrecords `n_material_slots` + `material_indices_used` (read off the EVALUATED mesh,so modifier-added indices count) and warns when a mesh carries slots no polygondiff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.mdindex f969eeb4..ba5fdca0 100644--- a/harness/docs/RUNBOOK.md+++ b/harness/docs/RUNBOOK.md@@ -360,8 +360,10 @@ model, produced the zero — check `cell.json`'s `error`).* **New language**: enum in `contracts/common.py::Language` (+ `TRACK_LANGUAGES`,`ENTRY_FILE`, `LANGUAGE_LABEL`), frame in `conventions.LANGUAGE_FRAME`;- `languages/<lang>/{__init__.py, wrappers/}` (one merged module per language;- the contract text is `prompts/<lang>/contract.md`) implementing `LanguageRuntime`; branch in `languages/base.py::get_runtime`;+ `languages/<lang>/__init__.py` (one merged module per language; the contract text is+ `prompts/<lang>/contract.md`) implementing `LanguageRuntime`, and a python-executed build+ wrapper beside the others in `languages/wrappers/` (import `_wrapper_common`; read its report+ with `_common.compose_build_result`, which publishes the final `build.json`); branch in `languages/base.py::get_runtime`;`prompts/<lang>/contract.md` + `cookbook.md` (every snippet must run —`tests/prompts` executes them); part→file mapping via `runtime.file_for_part`(blender has it; `tracks/prompting.file_for_target_factory` picks it up and mapsdiff --git a/harness/tests/blender_cadquery/test_blender_layout.py b/harness/tests/blender_cadquery/test_blender_layout.pyindex f4a6b2bc..2b4b5185 100644--- a/harness/tests/blender_cadquery/test_blender_layout.py+++ b/harness/tests/blender_cadquery/test_blender_layout.py@@ -128,26 +128,31 @@ def test_wrapper_maps_errors_to_the_failing_src_file(tmp_path, monkeypatch) -> N(src / "parts").mkdir(parents=True)(src / "model.py").write_text("from parts.leg import build_leg\nbuild_leg()\n")(src / "parts" / "leg.py").write_text("def build_leg():\n x = {}\n return x['missing']\n")- err = wrapper.run_script(str(src / "model.py"))++ def run(script):+ exc, _ = wrapper.run_script(script)+ return wrapper.script_error(exc, script)++ err = run(str(src / "model.py"))assert err["error_type"] == "KeyError" and err["error_file"] == "src/parts/leg.py" and err["error_line"] == 3assert err["error_source"] == "return x['missing']"# syntax error inside a part file imported by model.py → reported against the part file(src / "parts" / "leg.py").write_text("def build_leg(:\n pass\n")for name in [m for m in sys.modules if m.startswith("parts")]:del sys.modules[name]- err = wrapper.run_script(str(src / "model.py"))+ err = run(str(src / "model.py"))assert err["error_type"] == "SyntaxError" and err["error_file"] == "src/parts/leg.py" and err["error_line"] == 1# missing builder → hint names the file and the function(src / "parts" / "leg.py").write_text("def build_legs():\n pass\n")- err = wrapper.run_script(str(src / "model.py"))+ err = run(str(src / "model.py"))assert err["error_type"] == "ImportError" and err["error_file"] == "src/model.py" and err["error_line"] == 1assert "def build_leg()" in err["error_message"] and "parts/leg.py" in err["error_message"]# missing module → hint says to create the file(src / "model.py").write_text("import math\nfrom parts.armrest import build_armrest\n")- err = wrapper.run_script(str(src / "model.py"))+ err = run(str(src / "model.py"))assert err["error_type"] in ("ModuleNotFoundError", "ImportError")assert err["error_line"] == 2 and "src/parts/armrest.py" in err["error_message"]- assert wrapper.src_relative(str(src / "parts" / "x.py"), str(src)) == "src/parts/x.py"- assert wrapper.src_relative(str(tmp_path / "other.py"), str(src)) is None+ (src / "model.py").write_text("import sys\nsys.exit(0)\n") # not a failure: the scene is what was built+ assert wrapper.run_script(str(src / "model.py")) == (None, None)for name in [m for m in sys.modules if m == "parts" or m.startswith("parts.")]:del sys.modules[name]diff --git a/harness/tests/blender_cadquery/test_cadquery_runtime.py b/harness/tests/blender_cadquery/test_cadquery_runtime.pyindex 38d01111..6527ffac 100644--- a/harness/tests/blender_cadquery/test_cadquery_runtime.py+++ b/harness/tests/blender_cadquery/test_cadquery_runtime.py@@ -144,8 +144,10 @@ def _wrapper_module():return mod-def test_wrapper_error_file_is_workspace_relative(tmp_path) -> None:+def test_wrapper_error_file_is_workspace_relative(tmp_path, monkeypatch) -> None:"""error_file must be ``src/<file>`` (like every other runtime) and point at the innermost src/ frame."""+ monkeypatch.setattr(sys, "path", list(sys.path)) # run_script edits sys.path; keep the test process clean+ monkeypatch.setattr(sys, "dont_write_bytecode", sys.dont_write_bytecode)mod = _wrapper_module()src = tmp_path / "src"src.mkdir()@@ -155,20 +157,25 @@ def test_wrapper_error_file_is_workspace_relative(tmp_path) -> None:assert mod.src_relative(str(src / "parts" / "leg.py"), str(src)) == "src/parts/leg.py"assert mod.src_relative(str(tmp_path / "other.py"), str(src)) is Noneassert mod.entry_relative(str(src / "model.py")) == "src/model.py"- err, ns = mod.run_script(str(src / "model.py"))- assert err is not None and ns == {}++ def run(script):+ exc, ns = mod.run_script(script)+ assert exc is not None and ns is None+ return mod.script_error(exc, script)++ err = run(str(src / "model.py"))assert err["error_type"] == "RuntimeError" and err["error_file"] == "src/helpers.py" and err["error_line"] == 2assert "raise RuntimeError" in err["error_source"] and "helpers.py" in err["traceback"]# an error raised by model.py itself still maps to src/model.py (and so does a SyntaxError)(src / "model.py").write_text("import math\nx = 1 / 0\n")- err, _ = mod.run_script(str(src / "model.py"))+ err = run(str(src / "model.py"))assert err["error_file"] == "src/model.py" and err["error_line"] == 2(src / "model.py").write_text("result = (\n")- err, _ = mod.run_script(str(src / "model.py"))+ err = run(str(src / "model.py"))assert err["error_type"] == "SyntaxError" and err["error_file"] == "src/model.py"+ # sys.exit(0) leaves no globals to read `result` from (main() reports it as SystemExit)(src / "model.py").write_text("import sys\nsys.exit(0)\n")- err, _ = mod.run_script(str(src / "model.py"))- assert err["error_type"] == "SystemExit" and err["error_file"] == "src/model.py"+ assert mod.run_script(str(src / "model.py")) == (None, None)@needs_cqdiff --git a/harness/tests/blender_cadquery/test_material_slots.py b/harness/tests/blender_cadquery/test_material_slots.pyindex aad0e0ac..7048fd33 100644--- a/harness/tests/blender_cadquery/test_material_slots.py+++ b/harness/tests/blender_cadquery/test_material_slots.py@@ -16,7 +16,7 @@ import pytestfrom codeverse3d.languages.blender import BlenderRuntime-CENSUS = Path(__file__).resolve().parents[2] / "codeverse3d" / "languages" / "blender" / "wrappers" / "_census.py"+CENSUS = Path(__file__).resolve().parents[2] / "codeverse3d" / "languages" / "wrappers" / "_census.py"def _census_module() -> Any:diff --git a/harness/tests/urdf_joints/test_live_blender.py b/harness/tests/urdf_joints/test_live_blender.pyindex d6d230f8..4803eadc 100644--- a/harness/tests/urdf_joints/test_live_blender.py+++ b/harness/tests/urdf_joints/test_live_blender.py@@ -125,3 +125,36 @@ def test_wrapper_unsafe_link_name_is_a_build_error(tmp_path):assert not build["ok"] and build["error_type"] == "UnsafeLinkName"assert "../evil" in build["error_message"]assert not (out / "meshes").exists() and not (tmp_path / "evil.glb").exists()+++@needs_blender+def test_links_script_that_calls_sys_exit_0_still_builds(tmp_path):+ """``sys.exit(0)`` ends the script, not the build: the objects it made are the links+ (the blender language's rule; this wrapper used to report it as a SystemExit error).+ The run is seeded like the blender language's, so ``random`` draws the same numbers."""+ import json as _json+ import subprocess++ from codeverse3d.languages.urdf import WRAPPER++ (tmp_path / "robot.urdf").write_text('<robot name="r"><link name="base"/></robot>')+ (tmp_path / "model.py").write_text(+ "import random, sys\nimport bpy\n"+ "bpy.ops.mesh.primitive_cube_add(size=0.2 + random.random())\n"+ "bpy.context.active_object.name = 'base'\n"+ "sys.exit(0)\n"+ "raise RuntimeError('never reached')\n")+ out = tmp_path / "art"+ subprocess.run(+ [get_settings().resolve_blender(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",+ "--script", str(tmp_path / "model.py"), "--urdf", str(tmp_path / "robot.urdf"), "--out", str(out)],+ capture_output=True, text=True, timeout=180, check=False)+ build = _json.loads((out / "build.json").read_text())+ assert build["ok"] and build["error_type"] == "", build+ census = _json.loads((out / "census.json").read_text())+ import random++ random.seed(0)+ assert census["links"]["base"]["bbox_max"][0] == pytest.approx((0.2 + random.random()) / 2, abs=1e-5)+ assert (out / "meshes" / "base.glb").is_file()+ assert any("has no material" in w for w in census["warnings"]) # the blender language's census