Official Codebase of 3DCodeVerse
Python
spatial: one render-mode list, one NodeResult, and 400 lines nothing called
gaoypeng024314814768
diff --git a/harness/codeverse/contracts/artifacts.py b/harness/codeverse/contracts/artifacts.pyindex a3f05c0e..b1c82138 100644--- a/harness/codeverse/contracts/artifacts.py+++ b/harness/codeverse/contracts/artifacts.py@@ -106,10 +106,16 @@ class Measurement(BaseModel):extra: dict[str, Any] = Field(default_factory=dict)+#: every mode the object rig draws (runtime_js/render_glb.mjs MODES, pinned by+#: tests/spatial_tools/test_tools.py). The tool layer advertised "depth" from the+#: first commit; no renderer ever had it.+RENDER_MODES = ("shaded", "wire", "normals", "silhouette", "clay")++class RenderView(BaseModel):name: strpath: str- mode: str = "shaded" # shaded | wire | normals | silhouette | depth | clay+ mode: str = "shaded"width: int = 0height: int = 0camera_position: Vec3 | None = Nonediff --git a/harness/codeverse/languages/urdf/wrappers/render_glb_bpy.py b/harness/codeverse/languages/urdf/wrappers/render_glb_bpy.pydeleted file mode 100644index 93ba9e22..00000000--- a/harness/codeverse/languages/urdf/wrappers/render_glb_bpy.py+++ /dev/null@@ -1,87 +0,0 @@-"""Headless-Blender fallback renderer (Workbench, studio light) for a GLB.--Usage (run BY THE HARNESS, never by agent code)::-- blender -b --factory-startup --python render_glb_bpy.py -- spec.json--``spec.json``: ``{"glb", "out_dir", "width", "height", "views":[{"name","az","el"}]}``.-Azimuth 0 = front (camera on -Y looking +Y in Blender's Z-up world), CCW from-above; elevation in degrees above the horizon. Writes ``out_dir/view_<name>.png``.-"""--import json-import math-import sys-from pathlib import Path--import bpy-from mathutils import Vector---def _clear_scene() -> None:- bpy.ops.wm.read_factory_settings(use_empty=True)---def _scene_bounds():- lo = Vector((math.inf,) * 3)- hi = Vector((-math.inf,) * 3)- for ob in bpy.data.objects:- if ob.type != "MESH":- continue- for c in ob.bound_box:- w = ob.matrix_world @ Vector(c)- lo = Vector(min(a, b) for a, b in zip(lo, w, strict=True))- hi = Vector(max(a, b) for a, b in zip(hi, w, strict=True))- if not math.isfinite(lo.x):- lo, hi = Vector((-0.5,) * 3), Vector((0.5,) * 3)- return lo, hi---def _look_at(cam, target: Vector) -> None:- direction = target - cam.location- cam.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()---def main() -> None:- argv = sys.argv[sys.argv.index("--") + 1 :]- spec = json.loads(Path(argv[0]).read_text())- out_dir = Path(spec["out_dir"])- out_dir.mkdir(parents=True, exist_ok=True)- _clear_scene()- bpy.ops.import_scene.gltf(filepath=spec["glb"])- lo, hi = _scene_bounds()- center = (lo + hi) / 2- radius = max((hi - lo).length / 2, 1e-3)-- scene = bpy.context.scene- scene.render.engine = "BLENDER_WORKBENCH"- shading = scene.display.shading- shading.light = "STUDIO"- shading.color_type = "MATERIAL"- shading.show_cavity = True- scene.display.render_aa = "8"- scene.render.resolution_x = int(spec.get("width", 512))- scene.render.resolution_y = int(spec.get("height", 512))- scene.render.film_transparent = False- scene.world = bpy.data.worlds.new("World")- scene.world.color = (0.92, 0.92, 0.92)-- cam_data = bpy.data.cameras.new("Cam")- cam_data.lens_unit = "FOV"- cam_data.angle = math.radians(40.0)- cam = bpy.data.objects.new("Cam", cam_data)- scene.collection.objects.link(cam)- scene.camera = cam- dist = radius / math.sin(cam_data.angle / 2) * 1.15-- for v in spec["views"]:- az, el = math.radians(v["az"]), math.radians(v["el"])- direction = Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)))- cam.location = center + direction * dist- _look_at(cam, center)- scene.render.filepath = str(out_dir / f"view_{v['name']}.png")- bpy.ops.render.render(write_still=True)- print(f"[render] {scene.render.filepath}")---main()diff --git a/harness/codeverse/skills/cv3d-threejs-shader-traps/SKILL.md b/harness/codeverse/skills/cv3d-threejs-shader-traps/SKILL.mdindex 19cf8c56..0881f641 100644--- a/harness/codeverse/skills/cv3d-threejs-shader-traps/SKILL.md+++ b/harness/codeverse/skills/cv3d-threejs-shader-traps/SKILL.md@@ -119,8 +119,8 @@ Verified against this runtime on 2026-08-25 — believing them costs a repair roThe gate proves your shader **compiles and is bound**. It says nothing about whether it is*visible* or *right*: colours crushed by the ACES plus sRGB output chain, transparent waterz-fighting the shore, a patched material whose clone lost its `onBeforeCompile`, a shared-program cache key, an effect placed outside every camera's frustum. There is no agent tool for-the counterfactual "strip the shader and diff the pixels" probe, so look at the frames:+program cache key, an effect placed outside every camera's frustum. Nothing in the harness+renders the scene without your shader to compare against, so look at the frames yourself:`scene_views` (or `render_views`) at two different times, and check that the thing you wrotechanged something.diff --git a/harness/codeverse/spatial/_render_common.py b/harness/codeverse/spatial/_render_common.pyindex 52e54f90..b2918157 100644--- a/harness/codeverse/spatial/_render_common.py+++ b/harness/codeverse/spatial/_render_common.py@@ -4,8 +4,7 @@workspaces, same browser through the scene host) and the graphics build(``languages/_gl_common`` via ``gl_render``) all repeat the same four chores:resolve the output directory, turn ``ViewPreset``s into the driver's camera-JSON, read a driver's JSON side-car back, and build the labelled contact sheet-with the settings' grid. They live here once so the flavours differ only in+JSON, and build the labelled contact sheet with the settings' grid. They live here once so the flavours differ only inwhat they actually drive.Nothing in here talks to node — see ``spatial.node.run_node`` (objects) and@@ -20,7 +19,6 @@ from typing import Anyfrom codeverse.config import get_settingsfrom codeverse.conventions import ViewPreset-from codeverse.proc import read_json_or_nonefrom codeverse.spatial.sheet import contact_sheet@@ -40,11 +38,6 @@ def view_specs(views: Sequence[ViewPreset]) -> list[dict[str, Any]]:return [{"name": v.name, "azimuth": float(v.azimuth_deg), "elevation": float(v.elevation_deg)} for v in views]-def read_json(path: Path | str) -> dict[str, Any]:- """Parse a driver side-car (views.json / metrics.json); ``{}`` when absent."""- return read_json_or_none(path) or {}--def build_sheet(images: Sequence[tuple[str, str | Path]], out: Path | str) -> str | None:"""Labelled contact sheet at the configured grid (``settings.render.sheet_cols``/ ``sheet_tile``); ``None`` when there is nothing to show."""diff --git a/harness/codeverse/spatial/complexity.py b/harness/codeverse/spatial/complexity.pyindex 1602a29f..cc80232b 100644--- a/harness/codeverse/spatial/complexity.py+++ b/harness/codeverse/spatial/complexity.py@@ -56,7 +56,6 @@ __all__ = ["COMPLEXITY_VERSION","complexity_of_parts","complexity_of_glb",- "complexity_summary_line","band_of",]@@ -388,11 +387,3 @@ def complexity_of_glb(glb: Path | str) -> ComplexityVector:return complexity_of_parts(parts, scene=scene)-def complexity_summary_line(vec: ComplexityVector) -> str:- """One line for prompts, reports and the CLI."""- return (- f"complexity {vec.index:.2f} ({vec.band}) · {vec.part_count} parts"- f" · depth {vec.assembly_depth} · {vec.tri_count} tris · {vec.materials} materials"- f" · silhouette {vec.silhouette:.1f} · feature density {vec.feature_density:.0f}"- f" · {vec.symmetry_groups} repeat groups · hollowness {vec.hollowness:.2f}"- )diff --git a/harness/codeverse/spatial/connectivity.py b/harness/codeverse/spatial/connectivity.pyindex b9746efd..eae78827 100644--- a/harness/codeverse/spatial/connectivity.py+++ b/harness/codeverse/spatial/connectivity.py@@ -38,6 +38,7 @@ import trimeshfrom codeverse.contracts.artifacts import GateFinding, GateReport, Severityfrom codeverse.conventions import CONTACT_GAP_M, Frame+from codeverse.spatial import joints_collide as collidefrom codeverse.spatial.contract import frame_label, glb_vec_to_plan, language_framefrom codeverse.spatial.joints_collide import fcl_collision_object, inside_island, oriented_islandsfrom codeverse.spatial.measure import GlbLoadError, fmt_vec, solid_parts@@ -90,15 +91,6 @@ def _aabb_gap(a: trimesh.Trimesh, b: trimesh.Trimesh) -> float:return float(np.linalg.norm(np.maximum(lo, 0.0)))-def _fcl_available() -> bool:- try:- import fcl # noqa: F401-- return True- except Exception:- return False--def pair_distance(name_a: str,a: trimesh.Trimesh,@@ -114,15 +106,13 @@ def pair_distance(:func:`codeverse.spatial.joints_collide.fcl_collision_object`) so a callertesting many pairs builds each part's BVH once instead of once per pair."""- if _fcl_available():+ if collide._fcl is not None:try:- import fcl-oa = obj_a if obj_a is not None else fcl_collision_object(a)ob = obj_b if obj_b is not None else fcl_collision_object(b)- req = fcl.DistanceRequest(enable_nearest_points=True)- res = fcl.DistanceResult()- d = fcl.distance(oa, ob, req, res)+ req = collide._fcl.DistanceRequest(enable_nearest_points=True)+ res = collide._fcl.DistanceResult()+ d = collide._fcl.distance(oa, ob, req, res)pa, pb = res.nearest_pointsreturn PairDistance(name_a, name_b, float(max(d, 0.0)), tuple(map(float, pa)), tuple(map(float, pb)))except Exception:@@ -186,23 +176,6 @@ def penetration_depth(a: trimesh.Trimesh, b: trimesh.Trimesh, n: int = N_SAMPLESreturn worst_depth, worst_frac-def _components(names: list[str], edges: set[tuple[str, str]]) -> list[set[str]]:- parent = {n: n for n in names}-- def find(x: str) -> str:- while parent[x] != x:- parent[x] = parent[parent[x]]- x = parent[x]- return x-- for a, b in edges:- parent[find(a)] = find(b)- comps: dict[str, set[str]] = {}- for n in names:- comps.setdefault(find(n), set()).add(n)- return list(comps.values())--def _fmt_vec(v: tuple[float, float, float]) -> str:"""Millimetre-precision translation vector (shared formatter, 4 decimals)."""return fmt_vec(v, 4)@@ -282,7 +255,7 @@ def check_connectivity(data={"other": b, "depth_m": depth, "fraction_inside": frac},))# ---- components → floating parts- comps = _components(big, edges)+ comps = collide.components(big, edges)# TOUCHING the ground, not merely at-or-below it: the old one-sided `<= gap_m`# counted a part buried 1 m under the floor as grounded, so a model authored around# the origin instead of on it (a routine agent mistake, which the contract gatediff --git a/harness/codeverse/spatial/contract.py b/harness/codeverse/spatial/contract.pyindex 24fcd2f7..1fc0ef0f 100644--- a/harness/codeverse/spatial/contract.py+++ b/harness/codeverse/spatial/contract.py@@ -136,11 +136,6 @@ def _fmt_delta(v: np.ndarray) -> str:return ", ".join(f"{a}{d * 100:+.1f}cm" for a, d in zip(_AXES, v, strict=True))-#: shared formatters (``spatial.measure``): sizes in cm, translation vectors in m-_fmt_ext = fmt_extent_cm-_fmt_vec = fmt_vec--def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, language: str,check_center: bool = True) -> list[GateFinding]:"""WARN/ERROR findings for one box comparison (empty when within tolerance).@@ -159,7 +154,7 @@ def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, language:p_ctr = glb_vec_to_plan(plan.center, language)bits = []if ext_bad.any():- bits.append(f"size {_fmt_ext(p_ext + d_ext)} vs planned {_fmt_ext(p_ext)} cm (Δ {_fmt_delta(d_ext)})")+ bits.append(f"size {fmt_extent_cm(p_ext + d_ext)} vs planned {fmt_extent_cm(p_ext)} cm (Δ {_fmt_delta(d_ext)})")if ctr_bad:bits.append(f"centre off by ({_fmt_delta(d_ctr)})")hint = f"{what}: " + ("; ".join(bits))@@ -185,7 +180,7 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: fgate=GATE, severity=Severity.ERROR, target=target,message=f"plan part '{pp.name}' is missing from the GLB",fix_hint=f"create a part named exactly '{pp.name}'" + (f" (×{pp.instances} as {pp.name}_0..{pp.instances - 1})" if pp.instances > 1 else "")- + f" — {pp.role}; planned size {_fmt_ext(pp.bbox.extents)} cm",+ + f" — {pp.role}; planned size {fmt_extent_cm(pp.bbox.extents)} cm",data={"expected_instances": pp.instances},))continue@@ -227,13 +222,13 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: ffindings.append(GateFinding(gate=GATE, severity=Severity.WARN, target="overall",message=f"footprint centre is {m.footprint_offset_m * 100:.1f} cm off the up axis",- fix_hint=f"translate everything by {_fmt_vec(glb_vec_to_plan((-m.center[0], 0.0, -m.center[2]), language))} m "+ fix_hint=f"translate everything by {fmt_vec(glb_vec_to_plan((-m.center[0], 0.0, -m.center[2]), language))} m "f"({frame_label(language)}) to centre the footprint",data={"footprint_offset_m": m.footprint_offset_m, "frame": language_frame(language).value},))for r in extra:findings.append(GateFinding(gate=GATE, severity=Severity.INFO, target=r.name,- message=f"GLB part '{r.name}' is not in the plan ({_fmt_ext(np.subtract(r.bbox_max, r.bbox_min))} cm)"))+ message=f"GLB part '{r.name}' is not in the plan ({fmt_extent_cm(np.subtract(r.bbox_max, r.bbox_min))} cm)"))return findingsdiff --git a/harness/codeverse/spatial/frame_motion.py b/harness/codeverse/spatial/frame_motion.pyindex 8c7820df..3959a1b8 100644--- a/harness/codeverse/spatial/frame_motion.py+++ b/harness/codeverse/spatial/frame_motion.py@@ -83,7 +83,7 @@ def _load(path: Path) -> np.ndarray | None:def _pair_rows(entries: Sequence[dict[str, Any]], out_dir: Path) -> list[MotionRow]:by_name: dict[str, list[dict[str, Any]]] = {}for v in entries:- if not isinstance(v, dict) or v.get("kind") == "counterfactual" or "_nocustom" in str(v.get("name", "")):+ if not isinstance(v, dict):continueby_name.setdefault(str(v.get("name", "?")), []).append(v)rows: list[MotionRow] = []diff --git a/harness/codeverse/spatial/gl_render.py b/harness/codeverse/spatial/gl_render.pyindex 92f4cc05..4c7baf5a 100644--- a/harness/codeverse/spatial/gl_render.py+++ b/harness/codeverse/spatial/gl_render.py@@ -80,10 +80,6 @@ class GlResult(BaseModel):def judge_frames(self) -> list[GlFrame]:return [f for f in self.frames if f.judge]- @property- def has_nan(self) -> bool:- return any(f.nan or f.inf for f in self.frames)-class GlHostError(RuntimeError):"""Harness-side failure (runner missing, no GL at all) — not an agent error."""diff --git a/harness/codeverse/spatial/joints.py b/harness/codeverse/spatial/joints.pyindex 908adea7..8271ba98 100644--- a/harness/codeverse/spatial/joints.py+++ b/harness/codeverse/spatial/joints.py@@ -9,14 +9,12 @@ Import from here::* :mod:`codeverse.spatial.joints_sweep` — ``sweep_collisions`` (FCL + trimesh),``sweep_findings`` (→ GateFindings), ``motion_direction_check``.* :mod:`codeverse.spatial.joints_export` — ``urdf_to_glb`` (hierarchical GLB with joint- extras), ``render_poses`` (+ ``articulation_sheet.png``), ``joint_sweep_observation``.+ extras), ``render_poses`` (+ ``articulation_sheet.png``)."""from codeverse.spatial.joints_export import (ARTICULATION_SHEET_NAME,ZUP_TO_YUP,- blender_render_glb,- joint_sweep_observation,render_poses,robot_scene,urdf_to_glb,@@ -29,7 +27,6 @@ from codeverse.spatial.joints_model import (fk,link_world_meshes,load_urdf,- world_bboxes,)from codeverse.spatial.joints_poses import limit_poses, pose_label, pose_samplesfrom codeverse.spatial.joints_sweep import (@@ -45,7 +42,7 @@ from codeverse.spatial.joints_sweep import (__all__ = ["ARTICULATION_SHEET_NAME", "ZUP_TO_YUP", "Joint", "Link", "MotionCheck", "Overlap", "Robot", "SweepReport",- "SweepSummary", "UrdfError", "blender_render_glb", "fk", "joint_sweep_observation", "limit_poses",+ "SweepSummary", "UrdfError", "fk", "limit_poses","link_world_meshes", "load_urdf", "motion_direction_check", "pose_label", "pose_samples", "render_poses",- "robot_scene", "summary_text", "sweep_collisions", "sweep_findings", "urdf_to_glb", "world_bboxes",+ "robot_scene", "summary_text", "sweep_collisions", "sweep_findings", "urdf_to_glb",]diff --git a/harness/codeverse/spatial/joints_collide.py b/harness/codeverse/spatial/joints_collide.pyindex d6e467a0..c3d34a5b 100644--- a/harness/codeverse/spatial/joints_collide.py+++ b/harness/codeverse/spatial/joints_collide.py@@ -34,6 +34,25 @@ def backend_name() -> str:return "fcl" if _fcl is not None else "trimesh"+def components(names: list[str], edges: set[tuple[str, str]]) -> list[set[str]]:+ """Connected components of ``names`` under ``edges`` (union-find) — the contact+ graph of the connectivity gate and the fixed-joint groups of the pose sweep."""+ parent = {n: n for n in names}++ def find(x: str) -> str:+ while parent[x] != x:+ parent[x] = parent[parent[x]]+ x = parent[x]+ return x++ for a, b in edges:+ parent[find(a)] = find(b)+ comps: dict[str, set[str]] = {}+ for n in names:+ comps.setdefault(find(n), set()).add(n)+ return list(comps.values())++def fcl_collision_object(mesh: trimesh.Trimesh):"""``fcl.CollisionObject`` for ``mesh`` (identity transform; None whenpython-fcl is unavailable). Convex meshes get the cheap ``fcl.Convex``diff --git a/harness/codeverse/spatial/joints_export.py b/harness/codeverse/spatial/joints_export.pyindex 700625c2..b9a6b830 100644--- a/harness/codeverse/spatial/joints_export.py+++ b/harness/codeverse/spatial/joints_export.py@@ -11,21 +11,18 @@ Non-root link nodes carry ``extras.joint`` and the scene carriesfrom __future__ import annotations-import jsonimport sys-import time-from collections.abc import Callable, Sequence+from collections.abc import Sequencefrom pathlib import Pathfrom typing import Anyimport numpy as npimport trimesh-from codeverse.contracts.artifacts import RenderSet, RenderView+from codeverse.contracts.artifacts import RenderSetfrom codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset-from codeverse.proc import run_subprocess-from codeverse.spatial._render_common import build_sheet, out_directory, view_specs-from codeverse.spatial.joints_model import Joint, Robot, UrdfError, fk+from codeverse.spatial._render_common import out_directory+from codeverse.spatial.joints_model import Joint, Robot, fkfrom codeverse.spatial.joints_poses import limit_posesfrom codeverse.spatial.render import render_glbfrom codeverse.spatial.sheet import contact_sheet@@ -36,8 +33,6 @@ ZUP_TO_YUP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]],#: scene-graph base frame of the exported GLB (not a glTF node; must not collide with a link name)SCENE_BASE_FRAME = "__scene__"-Renderer = Callable[..., RenderSet]-def joint_extras(j: Joint) -> dict[str, Any]:return {@@ -102,48 +97,11 @@ def urdf_to_glb(robot: Robot, out_glb: Path | str, pose: dict[str, float] | None# ------------------------------------------------------------------ rendering-def blender_render_glb(glb: Path, out_dir: Path, *, views: Sequence[ViewPreset] | None = None, width: int = 512,- height: int = 512, sheet: bool = False, timeout_s: int = 180, **_: Any) -> RenderSet:- """Minimal headless-Blender (Workbench) renderer with the same signature- subset as ``render_glb``. Only used when a caller *explicitly* passes- ``renderer=blender_render_glb`` (e.g. to render without node/Chrome) — it is- never auto-selected."""- from codeverse.config import get_settings-- blender = get_settings().resolve_blender()- if not blender:- raise RuntimeError("no Blender binary found for the fallback renderer")- views = tuple(views or OBJECT_VIEWS_QUICK)- out_dir = out_directory(out_dir)- script = Path(__file__).resolve().parent.parent / "languages" / "urdf" / "wrappers" / "render_glb_bpy.py"- spec = {"glb": str(glb), "out_dir": str(out_dir), "width": width, "height": height,- "views": [{"name": v["name"], "az": v["azimuth"], "el": v["elevation"]} for v in view_specs(views)]}- spec_path = out_dir / "_render_spec.json"- spec_path.write_text(json.dumps(spec))- t0 = time.time()- cmd = [blender, "-b", "--factory-startup", "--python", str(script), "--", str(spec_path)]- proc = run_subprocess(cmd, cwd=out_dir, timeout_s=timeout_s)- if proc.timed_out:- raise RuntimeError(f"blender fallback render timed out after {timeout_s}s: {proc.stderr[-2000:]}")- if proc.returncode != 0:- raise RuntimeError(f"blender fallback render failed: {proc.stderr[-2000:] or proc.stdout[-2000:]}")- rs = RenderSet(renderer="blender-workbench", duration_ms=int((time.time() - t0) * 1000))- for v in views:- p = out_dir / f"view_{v.name}.png"- if not p.is_file():- raise RuntimeError(f"blender fallback render produced no {p.name}; stdout tail: {proc.stdout[-800:]}")- rs.views.append(RenderView(name=v.name, path=str(p), width=width, height=height))- if sheet:- rs.contact_sheet = build_sheet([(v.name, v.path) for v in rs.views], out_dir / "sheet.png")- return rs--def render_poses(robot: Robot,out_dir: Path | str,poses: list[tuple[str, dict[str, float]]] | None = None,*,- renderer: Renderer | None = None,views: Sequence[ViewPreset] | None = None,width: int = 512,height: int = 512,@@ -155,13 +113,12 @@ def render_poses(out_dir = out_directory(out_dir)poses = poses if poses is not None else limit_poses(robot)views = tuple(views or OBJECT_VIEWS_QUICK[:3])- render = renderer or render_glbresults: list[tuple[str, RenderSet]] = []tiles: list[tuple[str, Path]] = []for label, q in poses:safe = "".join(c if c.isalnum() or c in "-_@." else "_" for c in label)glb = urdf_to_glb(robot, out_dir / f"pose_{safe}.glb", q)- rs = render(glb, out_dir / f"pose_{safe}", views=views, width=width, height=height, sheet=False)+ rs = render_glb(glb, out_dir / f"pose_{safe}", views=views, width=width, height=height, sheet=False)results.append((label, rs))for v in rs.views:if sheet_view is None or v.name == sheet_view:@@ -170,66 +127,6 @@ def render_poses(return results-def _poses_for(robot, joints: list[str] | None) -> list[tuple[str, dict[str, float]]] | None:- """``limit_poses`` narrowed to ``joints`` (rest kept); ``None`` = the full sheet.-- An unknown joint name narrows to nothing but rest, which is a wrong-but-visible sheet- rather than a silent fallback to everything — the agent sees one tile and its typo.- """- if not joints:- return None- want = set(joints)- return [(label, q) for label, q in limit_poses(robot) if label == "rest" or label.split("@")[0] in want]---# ------------------------------------------------------------------ tool-shaped entry point-def joint_sweep_observation(ws, *, n_random: int = 8, seed: int = 0, render: bool = True, out_dir: Path | None = None,- joint: str | None = None, expected_direction: str | None = None,- joints: list[str] | None = None):- """Run the pose sweep on ``ws.artifacts/robot.urdf`` (+ ``meshes/``) and return an- ``Observation`` (``spatial.tools_scene`` wraps this as the ``joint_sweep`` tool).-- ``joints`` narrows the RENDER to those joints' limit poses (plus rest). The collision- sweep still covers every joint — a change to one joint can collide with another, and- that check is cheap. Rendering is not: every pose is a GLB export plus three views, so- a 10-joint object renders ~63 images per call, and agents call this 3-8 times a round.- Measured 2026-08-25: articulated rounds ran a median 1007 s against 497 s for static- objects, with the agent session — mostly waiting on sweeps — as the whole difference.- The tool has accepted ``joints`` since it was written; nothing consumed it.- """- from codeverse.spatial.joints_model import load_urdf- from codeverse.spatial.joints_poses import pose_samples- from codeverse.spatial.joints_sweep import (- motion_direction_check,- report_numbers,- summary_text,- sweep_collisions,- )- from codeverse.spatial.registry import Observation-- urdf = Path(ws.artifacts) / "robot.urdf"- if not urdf.is_file():- return Observation.error("joint_sweep: artifacts/robot.urdf not found — run `build` first")- try:- robot = load_urdf(urdf, Path(ws.artifacts) / "meshes")- report = sweep_collisions(robot, pose_samples(robot, n_random=n_random, seed=seed))- except UrdfError as e:- return Observation.error(f"joint_sweep: {e}")- text = summary_text(report)- numbers = report_numbers(report)- if joint and expected_direction:- mc = motion_direction_check(robot, joint, expected_direction)- text += "\n" + mc.message- numbers["motion_check"] = mc.model_dump(mode="json")- images: list[str] = []- if render:- d = Path(out_dir) if out_dir else Path(ws.artifacts) / "tool_scratch" / "joint_sweep"- render_poses(robot, d, poses=_poses_for(robot, joints))- images.append(str(d / ARTICULATION_SHEET_NAME))- ok = report.summary.max_penetration_m <= report.tol_m and not report.summary.floating_links- return Observation(ok=ok, text=text, numbers=numbers, images=images)--if __name__ == "__main__": # tiny manual CLI: python -m codeverse.spatial.joints_export robot.urdf out.glbfrom codeverse.spatial.joints_model import load_urdfdiff --git a/harness/codeverse/spatial/joints_model.py b/harness/codeverse/spatial/joints_model.pyindex bd1d32d2..5cb787b6 100644--- a/harness/codeverse/spatial/joints_model.py+++ b/harness/codeverse/spatial/joints_model.py@@ -139,11 +139,6 @@ class Joint:T[:3, 3] = self.axis * qreturn T- def clamp(self, q: float) -> float:- if self.type in ("revolute", "prismatic") and self.lower is not None and self.upper is not None:- return min(max(q, self.lower), self.upper)- return q-@dataclassclass Link:@@ -152,7 +147,6 @@ class Link:submeshes: list[trimesh.Trimesh] = field(default_factory=list) # per-material pieces, LINK frame — used for exportvisual_origin: np.ndarray = field(default_factory=lambda: np.eye(4))mesh_file: str | None = None- has_collision: bool = False@propertydef tri_count(self) -> int:@@ -190,18 +184,6 @@ class Robot:stack.extend(j.child for j in reversed(self.child_joints(cur)))return out- def chain(self, link: str) -> list[Joint]:- """Joints from the root down to ``link`` (empty for the root)."""- chain: list[Joint] = []- cur = link- while cur != self.root:- j = self.parent_joint(cur)- if j is None:- raise UrdfError(f"link {link!r} is not connected to root {self.root!r}")- chain.append(j)- cur = j.parent- return list(reversed(chain))-def meshed_links(self) -> list[str]:return [n for n, link in self.links.items() if link.mesh is not None]@@ -242,7 +224,7 @@ def _load_mesh_file(filename: str, urdf_dir: Path, meshes_dir: Path | None, scaldef _link_from_xml(el: ET.Element, urdf_dir: Path, meshes_dir: Path | None, *, load_meshes: bool) -> Link:name = el.get("name", "")- link = Link(name=name, has_collision=el.find("collision") is not None)+ link = Link(name=name)parts: list[trimesh.Trimesh] = []first_origin: np.ndarray | None = Nonefor vis in el.findall("visual"):@@ -356,7 +338,7 @@ def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, lo# ------------------------------------------------------------------ FK-def fk(robot: Robot, q: dict[str, float] | None = None, *, clamp: bool = False) -> dict[str, np.ndarray]:+def fk(robot: Robot, q: dict[str, float] | None = None) -> dict[str, np.ndarray]:"""World transform of every link frame for joint values ``q`` (missing → 0)."""q = q or {}unknown = set(q) - set(robot.joints)@@ -368,10 +350,7 @@ def fk(robot: Robot, q: dict[str, float] | None = None, *, clamp: bool = False)continuej = robot.parent_joint(name)assert j is not None- val = float(q.get(j.name, 0.0))- if clamp:- val = j.clamp(val)- out[name] = out[j.parent] @ j.origin @ j.motion(val)+ out[name] = out[j.parent] @ j.origin @ j.motion(float(q.get(j.name, 0.0)))return out@@ -386,15 +365,3 @@ def link_world_meshes(robot: Robot, q: dict[str, float] | None = None) -> dict[sm.apply_transform(T[name])out[name] = mreturn out---def world_bboxes(robot: Robot, q: dict[str, float] | None = None) -> dict[str, tuple[np.ndarray, np.ndarray]]:- """Per-link world AABB (min, max) at pose ``q``."""- T = fk(robot, q)- out = {}- for name, link in robot.links.items():- if link.mesh is None:- continue- pts = trimesh.transform_points(link.mesh.vertices, T[name])- out[name] = (pts.min(axis=0), pts.max(axis=0))- return outdiff --git a/harness/codeverse/spatial/joints_sweep.py b/harness/codeverse/spatial/joints_sweep.pyindex 87890ef6..7f710cb7 100644--- a/harness/codeverse/spatial/joints_sweep.py+++ b/harness/codeverse/spatial/joints_sweep.py@@ -80,27 +80,6 @@ class MotionCheck(BaseModel):# ------------------------------------------------------------------ sweep-def _components(links: list[str], edges: set[tuple[str, str]]) -> dict[str, int]:- parent = {n: n for n in links}-- def find(x: str) -> str:- while parent[x] != x:- parent[x] = parent[parent[x]]- x = parent[x]- return x-- for a, b in edges:- ra, rb = find(a), find(b)- if ra != rb:- parent[ra] = rb- roots = {}- out = {}- for n in links:- r = find(n)- out[n] = roots.setdefault(r, len(roots))- return out--def sweep_collisions(robot: Robot,poses: list[dict[str, float]],@@ -123,7 +102,8 @@ def sweep_collisions(islands = {n: len(bodies[n].islands) for n in names}# links joined only by fixed joints never move relative to each other: their overlap is# structural and is measured once (at rest when the sweep has a rest pose, else first pose)- rigid_group = _components(list(robot.links), {(j.parent, j.child) for j in robot.joints.values() if j.type == "fixed"})+ comps = collide.components(list(robot.links), {(j.parent, j.child) for j in robot.joints.values() if j.type == "fixed"})+ rigid_group = {n: i for i, comp in enumerate(comps) for n in comp}labels = [pose_label(robot, q) for q in poses]rigid_pose = labels.index("rest") if "rest" in labels else 0diff --git a/harness/codeverse/spatial/mcp_server.py b/harness/codeverse/spatial/mcp_server.pyindex 059961d5..2415e368 100644--- a/harness/codeverse/spatial/mcp_server.py+++ b/harness/codeverse/spatial/mcp_server.py@@ -23,7 +23,7 @@ from typing import Anyfrom PIL import Imagefrom codeverse.spatial.observe import fmt_numbers-from codeverse.spatial.registry import Observation, ToolContext, ToolDef, list_tools+from codeverse.spatial.registry import Observation, ToolContext, list_toolsfrom codeverse.spatial.tool_common import spec_dictfrom codeverse.workspace import Workspace@@ -73,16 +73,12 @@ def observation_content(obs: Observation) -> list[Any]:return blocks-def mcp_tools(ctx: ToolContext) -> list[ToolDef]:- return list_tools(track=ctx.track, language=ctx.language)--def make_server(ctx: ToolContext):"""Low-level MCP ``Server`` wired to the registry for ``ctx``."""from mcp import typesfrom mcp.server.lowlevel import Server- defs = {t.name: t for t in mcp_tools(ctx)}+ defs = {t.name: t for t in list_tools(track=ctx.track, language=ctx.language)}async def on_list_tools(_req_ctx: Any, _params: Any) -> types.ListToolsResult:tools = [types.Tool(name=t.name, description=f"({t.cost_hint}) {t.describe()}", input_schema=t.schema())@@ -123,7 +119,7 @@ def main(argv: list[str] | None = None) -> int:return 2ctx = build_context(ws, track=ns.track, language=ns.language, round_index=ns.round_index)if ns.list:- print(json.dumps([{"name": t.name, "description": t.describe(), "schema": t.schema()} for t in mcp_tools(ctx)], indent=1))+ print(json.dumps([{"name": t.name, "description": t.describe(), "schema": t.schema()} for t in list_tools(track=ctx.track, language=ctx.language)], indent=1))return 0asyncio.run(serve_stdio(ctx))return 0diff --git a/harness/codeverse/spatial/measure.py b/harness/codeverse/spatial/measure.pyindex a40ebfd1..82d9c971 100644--- a/harness/codeverse/spatial/measure.py+++ b/harness/codeverse/spatial/measure.py@@ -383,9 +383,6 @@ def fmt_vec(v: Any, digits: int = 3) -> str:return "(" + ", ".join(f"{round(float(x), digits) + 0.0:+.{digits}f}" for x in v) + ")"-_fmt_ext = fmt_extent_cm # legacy private alias--def measure_summary_table(m: Measurement, max_rows: int = 30) -> str:"""Compact markdown table for prompts (judge/agent): totals + per-part rows.@@ -393,7 +390,7 @@ def measure_summary_table(m: Measurement, max_rows: int = 30) -> str:capped at ``max_rows`` (largest parts first, then an "… n more" line)."""lines = [- f"overall: {_fmt_ext(m.extents)} cm (W×H×D, Y-up) · centre ({m.center[0]:.3f}, {m.center[1]:.3f}, {m.center[2]:.3f}) m"+ f"overall: {fmt_extent_cm(m.extents)} cm (W×H×D, Y-up) · centre ({m.center[0]:.3f}, {m.center[1]:.3f}, {m.center[2]:.3f}) m"f" · {m.tri_count} tris · {len(m.parts)} parts · {m.n_islands} islands"f" · ground gap {m.ground_gap_m * 1000:.1f} mm · footprint offset {m.footprint_offset_m * 1000:.1f} mm","",@@ -408,11 +405,11 @@ def measure_summary_table(m: Measurement, max_rows: int = 30) -> str:maxs = np.max([p.bbox_max for p in ps], axis=0)ext = maxs - minsif len(ps) == 1:- label, size_txt = key, _fmt_ext(ext)+ label, size_txt = key, fmt_extent_cm(ext)else:label = f"{key} ×{len(ps)} ({members[0]}..{members[-1].rsplit('_', 1)[-1]})"each = np.max([np.subtract(p.bbox_max, p.bbox_min) for p in ps], axis=0)- size_txt = f"{_fmt_ext(each)} each, span {_fmt_ext(ext)}"+ size_txt = f"{fmt_extent_cm(each)} each, span {fmt_extent_cm(ext)}"tris = sum(p.tri_count for p in ps)islands = sum(p.islands for p in ps)wt = "yes" if all(p.watertight for p in ps) else ("no" if not any(p.watertight for p in ps) else "some")diff --git a/harness/codeverse/spatial/node.py b/harness/codeverse/spatial/node.pyindex 47319b3f..316bf126 100644--- a/harness/codeverse/spatial/node.py+++ b/harness/codeverse/spatial/node.py@@ -16,7 +16,7 @@ import osimport reimport resourceimport subprocess-from dataclasses import dataclass, field+from dataclasses import dataclassfrom functools import lru_cachefrom pathlib import Pathfrom typing import Any@@ -59,7 +59,11 @@ class NodeResult:last_json: dict[str, Any] | Noneduration_ms: inttimed_out: bool = False- cmd: list[str] = field(default_factory=list)++ @property+ def summary(self) -> dict[str, Any]:+ """The driver's last stdout JSON line, ``{}`` when it printed none."""+ return self.last_json or {}@propertydef stdout_tail(self) -> str:@@ -207,7 +211,6 @@ def run_node(last_json=parse_last_json(proc.stdout),duration_ms=proc.duration_ms,timed_out=proc.timed_out,- cmd=cmd,)if result.timed_out:raise NodeError(f"node script {script.name} timed out after {timeout_s:.0f}s\n{result.stderr_tail}", result)diff --git a/harness/codeverse/spatial/probes.py b/harness/codeverse/spatial/probes.pyindex a30f474f..239c4459 100644--- a/harness/codeverse/spatial/probes.py+++ b/harness/codeverse/spatial/probes.py@@ -1,32 +1,22 @@-"""Scene probes: import/census gate, shader compile preflight, shader presence.+"""Scene probes: import/census gate and shader compile preflight.* ``probe_scene(ws)`` → (GateReport 'scene_probe', census) — the scene build gate* ``check_shaders(ws)`` → GateReport 'shader_preflight' (file:line + fix hints)-* ``shader_presence(ws)``→ Observation: counterfactual render (custom shaders- stripped) vs normal; pixel-diff fraction proves the effect is in the frame.-All three drive the node host (``runtime_js/*.mjs``) via ``run_scene_script``.+Both drive the node host (``runtime_js/*.mjs``) via ``run_scene_script``."""from __future__ import annotationsimport jsonimport time-from pathlib import Pathfrom typing import Anyfrom pydantic import BaseModel, Fieldfrom codeverse.contracts.artifacts import GateFinding, GateReport, Severity-from codeverse.contracts.plan import CameraPlanfrom codeverse.conventions import MAX_TRIS_SCENE-from codeverse.spatial.registry import Observation-from codeverse.spatial.render_scene import (- SceneRenderError,- read_metrics,- render_scene,- run_scene_script,-)+from codeverse.spatial.render_scene import SceneRenderError, run_scene_scriptfrom codeverse.workspace import WorkspacePROBE_GATE = "scene_probe"@@ -213,45 +203,3 @@ def shader_report(report: dict[str, Any], *, duration_ms: int = 0) -> GateReporttarget="scene", **comp))passed = bool(rep.get("ok")) and not any(f.severity == Severity.ERROR for f in findings)return GateReport(gate=gate, passed=passed, findings=findings, duration_ms=duration_ms)---def shader_presence(- ws: Workspace,- *,- out_dir: Path | None = None,- camera: CameraPlan | None = None,- time_s: float = 0.7,- width: int = 512,- height: int = 288,- threshold: float = 0.01,-) -> Observation:- """Counterfactual probe: render normally and with custom-shader materials- stripped; the fraction of changed pixels says whether the effect is visible.- ``present`` when diff ≥ ``threshold`` (calibrate with fixtures; 0.0 = invisible)."""- import numpy as np- from PIL import Image-- out = Path(out_dir) if out_dir else ws.artifacts / "tool_scratch" / "shader_presence"- rs = render_scene(ws, out, cameras=[camera] if camera else None, orbit=False, times=(time_s,),- width=width, height=height, sheet=False, fps_seconds=0, counterfactual=True)- metrics = read_metrics(out)- custom = (metrics.get("census") or {}).get("custom_materials", [])- pairs = [(v, nv) for v in rs.views if "_nocustom" not in v.name for nv in rs.views if nv.name == f"{v.name}_nocustom"]- if not pairs:- return Observation.error("shader_presence: no render pairs produced; is the scene booting? " + "; ".join(rs.console_errors[:3]))- results = []- images: list[str] = []- for v, nv in pairs:- a = np.asarray(Image.open(v.path).convert("RGB")).astype(int)- b = np.asarray(Image.open(nv.path).convert("RGB")).astype(int)- frac = float((np.abs(a - b).max(axis=2) > 12).mean())- results.append({"camera": v.name, "diff_frac": round(frac, 4), "present": frac >= threshold})- images += [v.path, nv.path]- best = max(r["diff_frac"] for r in results)- text = (f"custom-shader materials: {len(custom)} ({', '.join(m.get('on', '?') for m in custom[:6])}); "- f"pixel change when stripped: " + ", ".join(f"{r['camera']}={r['diff_frac']:.1%}" for r in results)- + (". PRESENT: the shader changes the frame." if best >= threshold else- ". NOT VISIBLE: stripping the custom shader changes nothing — it is not in any camera's frame (or is hidden/occluded)."))- if not custom:- text = "no custom shader materials found (ShaderMaterial / onBeforeCompile). " + text- return Observation(ok=True, text=text, numbers={"custom_materials": len(custom), "max_diff_frac": best, "per_camera": results, "threshold": threshold}, images=images)diff --git a/harness/codeverse/spatial/registry.py b/harness/codeverse/spatial/registry.pyindex 07cc5d0b..2278fc07 100644--- a/harness/codeverse/spatial/registry.py+++ b/harness/codeverse/spatial/registry.py@@ -21,7 +21,6 @@ from __future__ import annotationsimport inspectfrom collections.abc import Callablefrom dataclasses import dataclass, field-from pathlib import Pathfrom typing import Anyfrom pydantic import BaseModel, Field@@ -50,7 +49,10 @@ class ToolUnavailable(RuntimeError):Raised by ``tool_common.lazy`` (and anything built on it) and turned into a``tool <name> unavailable: ...`` Observation by :meth:`ToolDef.call` — tools- never have to catch it themselves.+ never have to catch it themselves. The boundary is real only for+ ``codeverse.languages`` (the runtimes) and ``codeverse.texturing``; everything+ under ``codeverse.spatial`` is imported eagerly (2026-08-29: string paths for+ intra-package imports hid ordinary imports from go-to-definition)."""@@ -68,15 +70,8 @@ class ToolContext:round_index: int = 0language: str = ""track: str = ""- scratch: Path | None = Noneextra: dict[str, Any] = field(default_factory=dict)- @property- def scratch_dir(self) -> Path:- d = self.scratch or (self.workspace.artifacts / "tool_scratch")- d.mkdir(parents=True, exist_ok=True)- return d-@dataclass(frozen=True)class ToolDef:diff --git a/harness/codeverse/spatial/render.py b/harness/codeverse/spatial/render.pyindex 27a4338b..c0d8a6fe 100644--- a/harness/codeverse/spatial/render.py+++ b/harness/codeverse/spatial/render.py@@ -18,12 +18,12 @@ from pathlib import Pathfrom typing import Anyfrom codeverse.config import get_settings-from codeverse.contracts.artifacts import RenderSet, RenderView+from codeverse.contracts.artifacts import RENDER_MODES, RenderSet, RenderViewfrom codeverse.conventions import OBJECT_VIEWS, ViewPreset+from codeverse.proc import sha256_filefrom codeverse.spatial._render_common import build_sheet, out_directory, view_specsfrom codeverse.spatial.node import NodeError, run_node, runtime_js_dir-MODES = ("shaded", "wire", "normals", "silhouette", "clay")BACKGROUNDS = ("studio", "white", "transparent")CACHE_VERSION = 4 # bump when the rig changes in a way that invalidates cached PNGs@@ -32,16 +32,8 @@ class RenderError(RuntimeError):"""Rendering failed (node/puppeteer error, bad GLB, bad arguments)."""-def _sha256_file(path: Path) -> str:- h = hashlib.sha256()- with path.open("rb") as fh:- for chunk in iter(lambda: fh.read(1 << 20), b""):- h.update(chunk)- return h.hexdigest()--def _cache_key(glb: Path, params: dict[str, Any]) -> str:- blob = json.dumps({"v": CACHE_VERSION, "glb": _sha256_file(glb), **params}, sort_keys=True)+ blob = json.dumps({"v": CACHE_VERSION, "glb": sha256_file(glb), **params}, sort_keys=True)return hashlib.sha256(blob.encode()).hexdigest()[:24]@@ -101,8 +93,8 @@ def render_glb(out_dir = Path(out_dir).resolve()if not glb.is_file():raise RenderError(f"GLB not found: {glb}")- if mode not in MODES:- raise RenderError(f"mode must be one of {MODES}, got {mode!r}")+ if mode not in RENDER_MODES:+ raise RenderError(f"mode must be one of {RENDER_MODES}, got {mode!r}")if background not in BACKGROUNDS:raise RenderError(f"background must be one of {BACKGROUNDS}, got {background!r}")view_list = list(views) if views is not None else list(OBJECT_VIEWS)@@ -211,26 +203,4 @@ def _restore_from_cache(cache_dir: Path, out_dir: Path) -> dict[str, Any] | Nonereturn record-def render_turntable(- glb: Path | str,- out: Path | str,- *,- n: int = 24,- elevation_deg: float = 18.0,- mode: str = "shaded",- width: int = 512,- height: int = 512,- fps: int = 12,-) -> Path:- """Render ``n`` azimuth steps and assemble ``out`` (.mp4 via ffmpeg, or .gif via PIL)."""- from codeverse.spatial.turntable import assemble_turntable-- out = Path(out)- frames_dir = out.parent / f".{out.stem}_frames"- frames_dir.mkdir(parents=True, exist_ok=True)- views = [ViewPreset(f"tt{i:03d}", 360.0 * i / n, elevation_deg) for i in range(n)]- rs = render_glb(glb, frames_dir, views=views, mode=mode, width=width, height=height, sheet=False)- return assemble_turntable([Path(v.path) for v in rs.views], out, fps=fps)---__all__ = ["render_glb", "render_turntable", "RenderError", "MODES", "BACKGROUNDS"]+__all__ = ["render_glb", "RenderError", "BACKGROUNDS"]diff --git a/harness/codeverse/spatial/render_scene.py b/harness/codeverse/spatial/render_scene.pyindex 9624feae..2321f407 100644--- a/harness/codeverse/spatial/render_scene.py+++ b/harness/codeverse/spatial/render_scene.py@@ -18,7 +18,6 @@ import jsonimport loggingimport osfrom collections.abc import Sequence-from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any@@ -26,9 +25,9 @@ from codeverse.config import get_settingsfrom codeverse.contracts.artifacts import RenderSet, RenderViewfrom codeverse.contracts.plan import BBox, CameraPlanfrom codeverse.conventions import SCENE_VIEWS, ViewPreset+from codeverse.proc import read_json_or_nonefrom codeverse.spatial._render_common import build_sheet, out_directory, view_specs-from codeverse.spatial._render_common import read_json as _read_json-from codeverse.spatial.node import NodeError, run_node, runtime_js_dir+from codeverse.spatial.node import NodeError, NodeResult, run_node, runtime_js_dirfrom codeverse.workspace import Workspacelog = logging.getLogger(__name__)@@ -44,17 +43,6 @@ class SceneRenderError(RuntimeError):"""The node driver could not run (missing node/deps, timeout, crash)."""-@dataclass-class NodeResult:- """Outcome of one node driver run; ``summary`` is the last stdout JSON line."""-- returncode: int- stdout: str- stderr: str- summary: dict[str, Any]- duration_ms: int--def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd: Path | None = None) -> NodeResult:"""Run ``runtime_js/<script>`` via ``codeverse.spatial.node.run_node`` (whichdelegates to ``codeverse.proc.run_subprocess``: own process group, group kill@@ -75,13 +63,13 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:if e.result is not None and e.result.timed_out:raise SceneRenderError(f"{script} timed out after {timeout_s:.0f}s\n{e.result.stderr_tail}") from eraise SceneRenderError(f"{script} could not run: {e}") from e- summary = r.last_json or {}+ summary = r.summaryif r.rc in (2, 3) or (r.rc != 0 and not summary):raise SceneRenderError(f"{script} failed (exit {r.rc}): {summary.get('error') if summary else ''}\n"f"stderr tail: {r.stderr_tail}\nstdout tail: {r.stdout[-1000:]}")- return NodeResult(r.rc, r.stdout, r.stderr, summary, r.duration_ms)+ return rdef _camera_json(cams: Sequence[CameraPlan]) -> str:@@ -122,7 +110,6 @@ def render_scene(sheet: bool = True,orbit_views: Sequence[ViewPreset] = SCENE_VIEWS,fps_seconds: float = 2.0,- counterfactual: bool = False,timeout_s: float | None = None,bounds: BBox | None = None,sheet_max_views: int = JUDGE_MAX_VIEWS,@@ -148,8 +135,6 @@ def render_scene("--width", str(width), "--height", str(height),"--fps-seconds", f"{fps_seconds:g}",]- if counterfactual:- args.append("--counterfactual")bounds = bounds or plan_bounds(ws)if bounds is not None:args += ["--bounds", _bounds_json(bounds)]@@ -165,8 +150,8 @@ def render_scene(if not (out_dir / "metrics.json").is_file():raisedriver_error = str(e).splitlines()[0][:500]- res = NodeResult(returncode=2, stdout="", stderr="", summary={"error": driver_error}, duration_ms=0)- metrics = _read_json(out_dir / "metrics.json")+ res = NodeResult(rc=2, stdout="", stderr="", last_json={"error": driver_error}, duration_ms=0)+ metrics = read_json_or_none(out_dir / "metrics.json") or {}_store_motion(out_dir, metrics)views: list[RenderView] = []for v in metrics.get("views", []):@@ -251,10 +236,9 @@ def select_judge_views(rs: RenderSet, max_n: int = JUDGE_MAX_VIEWS, *, orbit_nam"""Copy of ``rs`` with the views a judge should see (≤ ``max_n``), in priority order:authored cameras at the first time · the first two overview orbit views at that time· the first two authored cameras at the last time · remaining orbit / authored /- other views. Counterfactual ``*_nocustom`` views are never chosen. Tracks call- this before judging; the full set stays on disk."""+ other views. Tracks call this before judging; the full set stays on disk."""orbit = set(orbit_names if orbit_names is not None else [v.name for v in SCENE_VIEWS])- views = [v for v in rs.views if "_nocustom" not in v.name]+ views = list(rs.views)if not views or max_n <= 0:return rs.model_copy(update={"views": views[:max(max_n, 0)]})times = sorted({v.time_s if v.time_s is not None else 0.0 for v in views})@@ -293,7 +277,7 @@ def _mark_judge_views(views_json: Path, views: Sequence[RenderView]) -> None:def read_metrics(out_dir: Path) -> dict[str, Any]:"""Full instrument payload written by the driver (census, camera_checks, ...)."""- return _read_json(Path(out_dir) / "metrics.json")+ return read_json_or_none(Path(out_dir) / "metrics.json") or {}def metrics_path_for(rs: RenderSet) -> Path | None:diff --git a/harness/codeverse/spatial/scene_placement.py b/harness/codeverse/spatial/scene_placement.pyindex d2d9dff7..c3ff76ba 100644--- a/harness/codeverse/spatial/scene_placement.py+++ b/harness/codeverse/spatial/scene_placement.py@@ -260,11 +260,12 @@ def placement_census(ws: Workspace, *, force_probe: bool = False, timeout_s: floreturn census-def _setting_text(ws: Workspace) -> str:- plan = read_json_or_none(ws.plan_path)- if not isinstance(plan, dict):- return ""- return " ".join(str(plan.get(k) or "") for k in ("setting", "environment", "title"))+def setting_text(plan: Any) -> str:+ """The plan text the indoor/outdoor rule reads (``setting`` / ``environment`` /+ ``title``), from a plan dict or a ScenePlan; ``""`` for anything else."""+ if isinstance(plan, dict):+ return " ".join(str(plan.get(k) or "") for k in ("setting", "environment", "title"))+ return " ".join(str(getattr(plan, k, "") or "") for k in ("setting", "environment", "title"))def check_placement(ws: Workspace, *, indoor: bool | None = None, force_probe: bool = False, timeout_s: float = 60.0) -> GateReport:@@ -272,7 +273,7 @@ def check_placement(ws: Workspace, *, indoor: bool | None = None, force_probe: bt0 = time.time()census = placement_census(ws, force_probe=force_probe, timeout_s=timeout_s)if indoor is None:- indoor = infer_indoor(_setting_text(ws))+ indoor = infer_indoor(setting_text(read_json_or_none(ws.plan_path)))return placement_findings(census.get("placement") or {}, indoor=indoor, duration_ms=int((time.time() - t0) * 1000))@@ -284,8 +285,7 @@ def placement_gate_safe(census: dict[str, Any] | None, *, plan: Any = None) -> Gtable = (census or {}).get("placement")if not isinstance(table, dict):return None- text = " ".join(str(getattr(plan, k, "") or "") for k in ("setting", "environment", "title"))- return placement_findings(table, indoor=infer_indoor(text))+ return placement_findings(table, indoor=infer_indoor(setting_text(plan)))except Exception as e: # noqa: BLE001 — advisory instrumentation must not fail the roundlog.warning("scene placement gate failed: %s", e)return GateReport(gate=GATE, passed=True, findings=[diff --git a/harness/codeverse/spatial/sections.py b/harness/codeverse/spatial/sections.pyindex 3ea7e441..77baca18 100644--- a/harness/codeverse/spatial/sections.py+++ b/harness/codeverse/spatial/sections.py@@ -11,7 +11,6 @@ image — the cheap way to inspect interiors along a whole object.from __future__ import annotations-import timefrom collections.abc import Sequencefrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -22,7 +21,7 @@ from PIL import Image, ImageDrawfrom codeverse.spatial.measure import GlbLoadError, merged_mesh, solid_partsfrom codeverse.spatial.registry import Observation-from codeverse.spatial.sheet import load_font+from codeverse.spatial.sheet import contact_sheet, load_font_AXIS_INDEX = {"x": 0, "y": 1, "z": 2}#: which two axes are drawn (horizontal, vertical) for a slicing axis@@ -201,7 +200,6 @@ def cross_section(size: int = 512,) -> Observation:"""Slice the GLB at ``axis = at`` (fraction of the bbox, or meters if ``absolute``)."""- t0 = time.time()axis = axis.lower()if axis not in _AXIS_INDEX:return Observation.error(f"axis must be one of x|y|z, got {axis!r}")@@ -224,12 +222,12 @@ def cross_section(numbers = {"axis": axis, "at_m": round(at_m, 4), "n_loops": data.n_loops,"total_area_m2": round(data.total_area_m2, 6), "hollow_ratio": round(data.hollow_ratio, 3),"parts_cut": per_part}- return Observation(ok=True, text=text, numbers=numbers, images=[str(out)], duration_ms=int((time.time() - t0) * 1000))+ return Observation(ok=True, text=text, numbers=numbers, images=[str(out)])def slices_sheet(glb: Path | str, axis: str, n: int, out_png: Path | str, *, parts: Sequence[str] | None = None, tile: int = 320) -> Observation:- """``n`` evenly spaced sections along ``axis`` tiled into one labelled grid."""- t0 = time.time()+ """``n`` evenly spaced sections along ``axis`` tiled into one labelled grid+ (``sheet.contact_sheet``; each tile carries its own title, so no sheet labels)."""axis = axis.lower()if axis not in _AXIS_INDEX:return Observation.error(f"axis must be one of x|y|z, got {axis!r}")@@ -241,22 +239,18 @@ def slices_sheet(glb: Path | str, axis: str, n: int, out_png: Path | str, *, parif not sel:return Observation.error("slices_sheet: no mesh parts in the GLB")out = Path(out_png)- out.parent.mkdir(parents=True, exist_ok=True)- cols = min(n, 4)- rows = int(np.ceil(n / cols))- sheet = Image.new("RGB", (cols * tile, rows * tile), (255, 255, 255))numbers: dict[str, object] = {"axis": axis, "n": n, "slices": []}+ tiles: list[tuple[str, Path]] = []for i in range(n):frac = (i + 0.5) / nat_m = _resolve_at(sel, axis, frac, False)data = compute_section(sel, axis, at_m)tmp = out.with_name(f"{out.stem}_{i}.png")- draw_section(data, tmp, size=tile, title=f"{axis}={at_m:.3f} m ({frac:.2f})")- sheet.paste(Image.open(tmp), ((i % cols) * tile, (i // cols) * tile))- tmp.unlink(missing_ok=True)+ tiles.append((f"{axis}={at_m:.3f}", draw_section(data, tmp, size=tile, title=f"{axis}={at_m:.3f} m ({frac:.2f})")))numbers["slices"].append({"at_m": round(at_m, 4), "n_loops": data.n_loops, # type: ignore[attr-defined]"area_m2": round(data.total_area_m2, 6), "hollow_ratio": round(data.hollow_ratio, 3)})- sheet.save(out)+ contact_sheet(tiles, out, cols=min(n, 4), tile=tile, label=False)+ for _, tmp in tiles:+ tmp.unlink(missing_ok=True)summary = "; ".join(f"{s['at_m']:.3f}m: {s['n_loops']} loops, hollow {s['hollow_ratio']:.0%}" for s in numbers["slices"]) # type: ignore[index]- return Observation(ok=True, text=f"{n} sections along {axis}: {summary}", numbers=numbers, images=[str(out)],- duration_ms=int((time.time() - t0) * 1000))+ return Observation(ok=True, text=f"{n} sections along {axis}: {summary}", numbers=numbers, images=[str(out)])diff --git a/harness/codeverse/spatial/sheet.py b/harness/codeverse/spatial/sheet.pyindex aacdd42f..afd34f86 100644--- a/harness/codeverse/spatial/sheet.py+++ b/harness/codeverse/spatial/sheet.py@@ -6,7 +6,7 @@ under its tile, fixed tile size so the VLM sees consistent scale.This module is also the one home for shared PIL drawing bits: ``load_font``,:func:`write_gif` and the sheet geometry/palette constants (``LABEL_H``,``PAD``, ``BG``, ``LABEL_BG``, ``LABEL_FG``) are public and reused by-``spatial.gl_render``, ``spatial.turntable``, ``spatial.sections`` and+``spatial.gl_render``, ``spatial.sections`` and``judges.images``."""@@ -123,9 +123,8 @@ def contact_sheet(def write_gif(frames: Sequence[str | Path], out: Path | str, *, fps: int = 12, width: int | None = None) -> Path:"""Animated GIF from ``frames`` (adaptive 128-colour palette, looping).- THE gif writer: turntables (full-size frames) and the graphics preview- (``width`` downscales with BILINEAR) both use it. Raises ``ValueError``- without frames.+ THE gif writer (the graphics preview; ``width`` downscales with BILINEAR).+ Raises ``ValueError`` without frames."""if not frames:raise ValueError("write_gif: no frames")diff --git a/harness/codeverse/spatial/tool_common.py b/harness/codeverse/spatial/tool_common.pyindex e6fb8ba5..4d970798 100644--- a/harness/codeverse/spatial/tool_common.py+++ b/harness/codeverse/spatial/tool_common.py@@ -1,6 +1,7 @@-"""Shared plumbing for the spatial tools: context lookups, lazy imports of-sibling packages (render / joints / probes / runtimes) with a typed-``ToolUnavailable`` failure, render-output caching and plan/spec loading.+"""Shared plumbing for the spatial tools: context lookups, lazy imports of the+optional siblings (``codeverse.languages`` runtimes, ``codeverse.texturing``, the+node renderer) with a typed ``ToolUnavailable`` failure, render-output caching+and plan/spec loading.Tools never touch globals: everything flows through :class:`ToolContext`."""@@ -16,7 +17,7 @@ from typing import Anyfrom pydantic import ValidationError-from codeverse.contracts.artifacts import RenderSet, Severity+from codeverse.contracts.artifacts import RENDER_MODES, RenderSet, Severityfrom codeverse.contracts.plan import ArticulatedPlan, GraphicsPlan, Plan, ScenePlan, StaticPlanfrom codeverse.conventions import OBJECT_VIEWS, ViewPresetfrom codeverse.proc import read_json_or_none@@ -30,7 +31,6 @@ __all__ = []VIEW_BY_NAME: dict[str, ViewPreset] = {v.name: v for v in OBJECT_VIEWS}-RENDER_MODES = ("shaded", "wire", "normals", "silhouette", "depth", "clay")#: ``ToolUnavailable`` now lives in ``registry`` (``ToolDef.call`` catches it fordiff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.pyindex ec2c131f..c02902d4 100644--- a/harness/codeverse/spatial/tools.py+++ b/harness/codeverse/spatial/tools.py@@ -1,8 +1,6 @@-"""Core spatial tools registered with ``@tool``: build, measure, check_connectivity,-check_contract, cross_section. Rendering tools live in ``tools_render``, scene /-articulation tools in ``tools_scene``-(all imported at the bottom so ``import codeverse.spatial.tools`` registers every-tool).+"""Every spatial tool registered with ``@tool``, in sections: build / measure / gates /+sections · rendering · articulation · scenes · graphics · texturing · reference.+``import codeverse.spatial.tools`` registers all of them.House rules: observations are compact (errors first, fix hints attached), textnever contains absolute host paths (images are absolute — the harness converts),@@ -18,13 +16,18 @@ from typing import Anyfrom pydantic import BaseModel, Fieldfrom codeverse.config import fewer_turns_enabled, get_settings-from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet+from codeverse.contracts.artifacts import RENDER_MODES, BuildResult, GateReport, Measurementfrom codeverse.contracts.common import Language, Trackfrom codeverse.contracts.plan import StaticPlanfrom codeverse.contracts.spec import Specfrom codeverse.conventions import OBJECT_VIEWS, OBJECT_VIEWS_QUICKfrom codeverse.spatial.connectivity import check_connectivity as _check_connectivityfrom codeverse.spatial.contract import check_contract as _check_contract+from codeverse.spatial.frame_metrics import frame_summary_text+from codeverse.spatial.joints_export import ARTICULATION_SHEET_NAME, render_poses+from codeverse.spatial.joints_model import UrdfError, load_urdf+from codeverse.spatial.joints_poses import limit_poses, pose_samples+from codeverse.spatial.joints_sweep import report_numbers, summary_text, sweep_collisionsfrom codeverse.spatial.measure import GlbLoadError, measure_glb, measure_summary_tablefrom codeverse.spatial.observe import (build_failure_lines,@@ -39,7 +42,16 @@ from codeverse.spatial.observe import (text_observation,truncate,)+from codeverse.spatial.probes import check_shaders, probe_scenefrom codeverse.spatial.registry import NoArgs, Observation, ToolContext, ToolUsageError, tool+from codeverse.spatial.render_scene import read_metrics, render_scene+from codeverse.spatial.scene_placement import (+ infer_indoor,+ placement_findings,+ placement_table_text,+ setting_text,+)+from codeverse.spatial.scene_placement import placement_census as _placement_censusfrom codeverse.spatial.sections import cross_section as _cross_sectionfrom codeverse.spatial.sheet import contact_sheetfrom codeverse.spatial.silhouette import compare_silhouette as _compare_silhouette@@ -143,6 +155,39 @@ def _folded_checks(ctx: ToolContext, glb: Path, m: Measurement, language: str) -return [summary, *lines], numbers+_STDERR_TAIL_LINES = 25+_LINT_WARNS_SHOWN = 10+++def _lint_gate(ctx: ToolContext, rt: Any, *, verb: str) -> tuple[Observation | None, list[str]]:+ """Lint before any build-running tool builds: (refusal observation | None, warning+ lines). Lint ERRORs skip the build (docs/DECISIONS.md L5) and are recorded as the+ LATEST build status — without that the previous round's build_last.json (ok: true)+ + object.glb stayed readable as current."""+ ws = ctx.workspace+ lint: GateReport = rt.lint(ws)+ errs = lint_lines(lint, ws.root, errors_only=True)+ warns = lint_lines(lint, ws.root, errors_only=False)+ if not errs:+ return None, warns+ ws.write_json(ws.artifacts / "build_last.json",+ BuildResult(ok=False, language=language_of(ctx), error_type="LintError",+ error_message="\n".join(errs)[:4000]))+ text = f"LINT FAILED — fix these before {verb}:\n" + "\n".join(errs)+ if warns:+ text += "\nwarnings:\n" + "\n".join(warns[:_LINT_WARNS_SHOWN])+ return text_observation(text, ok=False, numbers={"stage": "lint", "lint_errors": len(errs)}), warns+++def _build_failed(ctx: ToolContext, br: BuildResult, warns: list[str]) -> Observation:+ """The BUILD FAILED observation of every build-running tool; ``error_file`` is+ workspace-relative (house rule: text never carries absolute host paths)."""+ ws = ctx.workspace+ return text_observation(build_failure_lines(br, ws.root, warns, tail_n=_STDERR_TAIL_LINES), ok=False, limit=3000,+ numbers={"stage": "build", "ok": False, "duration_ms": br.duration_ms, "error_type": br.error_type,+ "error_file": error_file_display(br.error_file, ws.root), "error_line": br.error_line})++@tool("build", NoArgs, "Lint + build the code in src/ with the language runtime, export artifacts/object.glb and measure it. Call after every edit.", cost_hint="slow",describe_extra=lambda: _BUILD_INCLUDES_CHECKS if fewer_turns_enabled() else "")def build(ctx: ToolContext, args: NoArgs) -> Observation:@@ -150,26 +195,14 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:ws = ctx.workspacelanguage = language_of(ctx)rt = lazy("codeverse.languages", "get_runtime")(language)- lint: GateReport = rt.lint(ws)- lint_errors = lint_lines(lint, ws.root, errors_only=True)- lint_warns = lint_lines(lint, ws.root, errors_only=False)- if lint_errors:- # record the refusal as the LATEST build status: without this the previous- # round's build_last.json (ok: true) + object.glb stayed readable as current- ws.write_json(ws.artifacts / "build_last.json",- BuildResult(ok=False, language=language, error_type="LintError",- error_message="\n".join(lint_errors)[:4000]))- text = "LINT FAILED — fix these before building:\n" + "\n".join(lint_errors)- if lint_warns:- text += "\nwarnings:\n" + "\n".join(lint_warns[:10])- return text_observation(text, ok=False, numbers={"stage": "lint", "lint_errors": len(lint_errors)})+ refused, lint_warns = _lint_gate(ctx, rt, verb="building")+ if refused is not None:+ return refusedbr: BuildResult = rt.build(ws, timeout_s=get_settings().limits.build_timeout_s)ws.write_json(ws.artifacts / "build_last.json", br)- numbers: dict[str, Any] = {"stage": "build", "ok": br.ok, "duration_ms": br.duration_ms}if not br.ok:- lines = build_failure_lines(br, ws.root, lint_warns, tail_n=_STDERR_TAIL_LINES)- numbers.update({"error_type": br.error_type, "error_file": error_file_display(br.error_file, ws.root), "error_line": br.error_line})- return text_observation(lines, ok=False, numbers=numbers, limit=3000)+ return _build_failed(ctx, br, lint_warns)+ numbers: dict[str, Any] = {"stage": "build", "ok": br.ok, "duration_ms": br.duration_ms}if not br.glb_path and language in _SCENE_LANGS + _GL_LANGS:# languages without a GLB deliverable: report the language's own artifactsok, extra_lines, extra_numbers = _no_glb_summary(ctx, br, language)@@ -190,7 +223,7 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:if m.extra.get("findings"):numbers["findings"] = m.extra["findings"]if lint_warns:- lines.append("lint warnings:\n" + "\n".join(lint_warns[:10]))+ lines.append("lint warnings:\n" + "\n".join(lint_warns[:_LINT_WARNS_SHOWN]))census_warn = br.census.get("warnings") if isinstance(br.census, dict) else Noneif census_warn:lines.append("build warnings:\n" + "\n".join(f"- {sanitize_text(str(w), ws.root)}" for w in list(census_warn)[:10]))@@ -276,17 +309,16 @@ def cross_section(ctx: ToolContext, args: CrossSectionArgs) -> Observation:return obs-# register the cookbook reader (the other tool modules merged in, 2026-08-28)--# ===================================================================== tools_render+# ===================================================================== rendering_DEFAULT_VIEWS = [v.name for v in OBJECT_VIEWS_QUICK]_MAX_SIZE = 1024+_MODE_DESC = " | ".join(RENDER_MODES)class RenderViewsArgs(BaseModel):views: list[str] = Field(default=list(_DEFAULT_VIEWS),description=f"view names from {[v.name for v in OBJECT_VIEWS]}")- mode: str = Field(default="shaded", description="shaded | wire | normals | silhouette | depth | clay")+ mode: str = Field(default="shaded", description=_MODE_DESC)isolate: list[str] = Field(default=[], description="render only these parts (others hidden)")explode: float = Field(default=0.0, ge=0.0, le=3.0, description="exploded view factor (0 = assembled)")size: int = Field(default=512, ge=128, le=_MAX_SIZE, description="image size in px (square)")@@ -309,7 +341,7 @@ def render_views(ctx: ToolContext, args: RenderViewsArgs) -> Observation:class RenderSheetArgs(BaseModel):- mode: str = Field(default="shaded", description="shaded | wire | normals | silhouette | depth | clay")+ mode: str = Field(default="shaded", description=_MODE_DESC)@tool("render_sheet", RenderSheetArgs, "One labelled 8-view contact sheet of the built object (all canonical views).", cost_hint="slow")@@ -348,6 +380,14 @@ def isolate(ctx: ToolContext, args: IsolateArgs) -> Observation:return obs+def _iou_verdict(res: dict[str, Any]) -> str:+ """Silhouette IoU → words, for compare_silhouette and compare_reference alike."""+ verdict = "good match" if res["iou"] >= 0.8 else "rough match" if res["iou"] >= 0.6 else "POOR match"+ if not res["reliable"]:+ verdict += " (IoU UNRELIABLE: background mask failed on one image — trust the pictures, not the number)"+ return verdict++class CompareSilhouetteArgs(BaseModel):view: str = Field(default="front", description="view to render in silhouette mode")reference_index: int = Field(default=0, ge=0, description="index into spec.references")@@ -368,73 +408,79 @@ def compare_silhouette(ctx: ToolContext, args: CompareSilhouetteArgs) -> Observaout_dir = render_cache_dir(ctx, glb, silhouette=args.view, ref=args.reference_index)diff = out_dir / f"silhouette_diff_{args.view}_ref{args.reference_index}.png"res = _compare_silhouette(rs.views[0].path, ref_path, diff_png=diff)- verdict = ("good match" if res["iou"] >= 0.8 else "rough match" if res["iou"] >= 0.6 else "poor match")- if not res["reliable"]:- verdict += " (UNRELIABLE: background mask failed on one image — judge visually)"- text = (f"silhouette '{args.view}' vs reference #{args.reference_index} ({ref_path.name}): IoU {res['iou']:.2f} → {verdict}; "+ text = (f"silhouette '{args.view}' vs reference #{args.reference_index} ({ref_path.name}): IoU {res['iou']:.2f} → {_iou_verdict(res)}; "f"aspect w/h render {res['render_aspect']:.2f} vs ref {res['ref_aspect']:.2f} (err {res['aspect_ratio_err']:.0%}). "f"Diff image: red = reference only, blue = render only. " + fmt_numbers({k: v for k, v in res.items() if k != "diff_png_path"}))images = image_budget([str(diff), rs.views[0].path])return Observation(ok=True, text=text, numbers={"view": args.view, **res}, images=images)-# ===================================================================== tools_scene-def _as_observation(result: Any, root, *, title: str) -> Observation:- """Normalise whatever a sibling returns (Observation / GateReport / RenderSet / dict / str)."""- if isinstance(result, Observation):- return result- if isinstance(result, GateReport):- return gate_observation(result, title=title)- if isinstance(result, RenderSet):- return render_observation(result, root, note=title)- if isinstance(result, BaseModel):- result = result.model_dump(mode="json")- if isinstance(result, dict):- images = [str(p) for p in (result.get("images") or []) if p]- errors = result.get("errors") or result.get("console_errors") or []- text = title + ": " + fmt_numbers({k: v for k, v in result.items() if k not in ("images",)}, max_items=40)- if errors:- text += "\nerrors:\n" + "\n".join(f" ! {str(e)[:200]}" for e in list(errors)[:10])- return Observation(ok=not errors, text=truncate(text), numbers=result, images=images[:6])- return Observation(ok=True, text=truncate(f"{title}: {result}"))---# --------------------------------------------------------------------------- articulated+# ===================================================================== articulationclass JointSweepArgs(BaseModel):joints: list[str] = Field(default=[], description="joint names to sweep (empty = all)")n_samples: int = Field(default=8, ge=2, le=32, description="poses per joint across its range")+def _poses_for(robot, joints: list[str] | None) -> list[tuple[str, dict[str, float]]] | None:+ """``limit_poses`` narrowed to ``joints`` (rest kept); ``None`` = the full sheet.++ An unknown joint name narrows to nothing but rest, which is a wrong-but-visible sheet+ rather than a silent fallback to everything — the agent sees one tile and its typo.+ """+ if not joints:+ return None+ want = set(joints)+ return [(label, q) for label, q in limit_poses(robot) if label == "rest" or label.split("@")[0] in want]++@tool("joint_sweep", JointSweepArgs, "Sweep URDF joints through their ranges: self-collision / limit findings for ALL joints, ""plus pose renders. Pass joints=[...] for the joints you changed — rendering every joint's poses is the slow part ""(three views per pose); the collision check always covers the whole robot.",tracks=(Track.ARTICULATED_OBJECT.value,), cost_hint="slow")def joint_sweep(ctx: ToolContext, args: JointSweepArgs) -> Observation:- fn = lazy("codeverse.spatial.joints", "joint_sweep_observation")+ """``joints`` narrows the RENDER to those joints' limit poses (plus rest). The collision+ sweep still covers every joint — a change to one joint can collide with another, and+ that check is cheap. Rendering is not: every pose is a GLB export plus three views, so+ a 10-joint object renders ~63 images per call, and agents call this 3-8 times a round.+ Measured 2026-08-25: articulated rounds ran a median 1007 s against 497 s for static+ objects, with the agent session — mostly waiting on sweeps — as the whole difference."""+ ws = ctx.workspace+ urdf = ws.artifacts / "robot.urdf"+ if not urdf.is_file():+ return Observation.error("joint_sweep: artifacts/robot.urdf not found — run `build` first")+ try:+ robot = load_urdf(urdf, ws.artifacts / "meshes")+ report = sweep_collisions(robot, pose_samples(robot, n_random=args.n_samples, seed=0))+ except UrdfError as e:+ return Observation.error(f"joint_sweep: {e}")out_dir = tool_out_dir(ctx, "joints")- res = fn(ctx.workspace, joints=args.joints or None, n_random=args.n_samples,- joint=args.joints[0] if len(args.joints) == 1 else None, out_dir=out_dir)- return _as_observation(res, ctx.workspace.root, title="joint sweep")+ render_poses(robot, out_dir, poses=_poses_for(robot, args.joints or None))+ ok = report.summary.max_penetration_m <= report.tol_m and not report.summary.floating_links+ return Observation(ok=ok, text=summary_text(report), numbers=report_numbers(report),+ images=[str(out_dir / ARTICULATION_SHEET_NAME)])-# --------------------------------------------------------------------------- scenes+# ===================================================================== scenes@tool("shader_probe", NoArgs, "Compile every GLSL/ShaderMaterial in the scene headlessly and report shader errors with line numbers.",languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")def shader_probe(ctx: ToolContext, args: NoArgs) -> Observation:- fn = lazy("codeverse.spatial.probes", "check_shaders")- res = fn(ctx.workspace)- return _as_observation(res, ctx.workspace.root, title="shader probe")+ return gate_observation(check_shaders(ctx.workspace), title="shader probe")@tool("scene_probe", NoArgs, "Load the scene headlessly: object/material/light census, triangle count, fps, console errors.",languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")def scene_probe(ctx: ToolContext, args: NoArgs) -> Observation:- fn = lazy("codeverse.spatial.probes", "probe_scene")- res = fn(ctx.workspace)- obs = _as_observation(res, ctx.workspace.root, title="scene probe")- census = obs.numbers.get("census") if isinstance(obs.numbers, dict) else None- if isinstance(census, dict) and census:- obs.text = obs.text + "\ncensus: " + fmt_numbers(census, max_items=30)+ res = probe_scene(ctx.workspace)+ # ok = the probe TOOL ran (SceneProbeResult semantics): a gate that fails on+ # agent-fixable findings stays ok; only harness/driver failures flip it+ obs = gate_observation(res.gate, title="scene probe")+ obs.ok = not res.errors+ if res.errors:+ obs.text += "\nerrors:\n" + "\n".join(f" ! {e[:200]}" for e in res.errors[:10])+ if res.census:+ obs.text += "\ncensus: " + fmt_numbers(res.census, max_items=30)+ obs.numbers["census"] = res.census+ obs.text = truncate(obs.text)return obs@@ -450,7 +496,6 @@ def scene_views(ctx: ToolContext, args: SceneViewsArgs) -> Observation:raise ToolUsageError("cameras must be authored | orbit | all", "scene_views(cameras='authored')")if not args.times or len(args.times) > 6:raise ToolUsageError("times must hold 1..6 values", "scene_views(times=[0.0, 1.5])")- render_scene = lazy("codeverse.spatial.render_scene", "render_scene")cams = Noneif args.cameras in ("authored", "all") and ctx.workspace.plan_path.is_file():try:@@ -462,17 +507,15 @@ def scene_views(ctx: ToolContext, args: SceneViewsArgs) -> Observation:key = f"{args.cameras}_{'_'.join(f'{t:g}' for t in args.times)}".replace(".", "p")out_dir = tool_out_dir(ctx, f"scene_{key}")rs = render_scene(ctx.workspace, out_dir, cameras=cams, orbit=orbit, times=tuple(args.times), sheet=True)- obs = _as_observation(rs, ctx.workspace.root, title=f"scene views ({args.cameras}, t={args.times})")+ obs = render_observation(rs, ctx.workspace.root, note=f"scene views ({args.cameras}, t={args.times})")table = _frame_table(out_dir)return obs.model_copy(update={"text": truncate(obs.text + "\n\n" + table)}) if table else obs-def _frame_table(out_dir) -> str:+def _frame_table(out_dir: Path) -> str:"""The deterministic numbers behind the pictures — exposure/coverage per camera plus themeasured motion between the times. Without them the agent is asked to LOOK at a sheet andguess whether its sway is visible or its dusk is too dark; with them it can read the answer."""- read_metrics = lazy("codeverse.spatial.render_scene", "read_metrics")- frame_summary_text = lazy("codeverse.spatial.frame_metrics", "frame_summary_text")try:metrics = read_metrics(out_dir)return frame_summary_text(metrics) if metrics else ""@@ -492,25 +535,20 @@ class CheckPlacementArgs(BaseModel):"obj.userData.placement = 'free'.",languages=(Language.SCENE_THREEJS.value,), cost_hint="fast")def check_placement(ctx: ToolContext, args: CheckPlacementArgs) -> Observation:- census_of = lazy("codeverse.spatial.scene_placement", "placement_census")- findings_of = lazy("codeverse.spatial.scene_placement", "placement_findings")- table_of = lazy("codeverse.spatial.scene_placement", "placement_table_text")- infer_indoor = lazy("codeverse.spatial.scene_placement", "infer_indoor")- census = census_of(ctx.workspace, force_probe=args.rebuild)+ census = _placement_census(ctx.workspace, force_probe=args.rebuild)indoor = Falseif ctx.workspace.plan_path.is_file():try:- plan = load_plan(ctx.workspace.plan_path)- indoor = infer_indoor(" ".join(str(getattr(plan, k, "") or "") for k in ("setting", "environment", "title")))+ indoor = infer_indoor(setting_text(load_plan(ctx.workspace.plan_path)))except ToolUsageError:indoor = Falsetable = census.get("placement") or {}- report = findings_of(table, indoor=indoor)+ report = placement_findings(table, indoor=indoor)obs = gate_observation(report, title="placement check")- return obs.model_copy(update={"text": truncate(obs.text + "\n\n" + table_of(table))})+ return obs.model_copy(update={"text": truncate(obs.text + "\n\n" + placement_table_text(table))})-# ===================================================================== tools_graphics+# ===================================================================== graphicsGRAPHICS_LANGS = (Language.GLSL_SHADER.value, Language.OPENGL_PYTHON.value)MAX_FRAMES = 8@@ -535,9 +573,6 @@ def _runtime(ctx: ToolContext):return get_runtime(lang)-_STDERR_TAIL_LINES = 25--def _run_build(ctx: ToolContext, *, times: list[float], preview: bool, width: int = 0, height: int = 0) -> tuple[Observation | None, BuildResult | None, list[str]]:"""Lint → build; returns (error observation | None, build, lint warnings).@@ -545,27 +580,16 @@ def _run_build(ctx: ToolContext, *, times: list[float], preview: bool, width: in"""ws = ctx.workspacert = _runtime(ctx)- lint: GateReport = rt.lint(ws)- errs = lint_lines(lint, ws.root, errors_only=True)- warns = lint_lines(lint, ws.root, errors_only=False)- if errs:- # the refusal is the latest build status (same reasoning as tools.build)- ws.write_json(ws.artifacts / "build_last.json",- BuildResult(ok=False, language=language_of(ctx), error_type="LintError",- error_message="\n".join(errs)[:4000]))- text = "LINT FAILED — fix these before rendering:\n" + "\n".join(errs)- if warns:- text += "\nwarnings:\n" + "\n".join(warns[:8])- return text_observation(text, ok=False, numbers={"stage": "lint", "lint_errors": len(errs)}), None, warns+ refused, warns = _lint_gate(ctx, rt, verb="rendering")+ if refused is not None:+ return refused, None, warnskw = {"times": times, "preview": preview}if width and height:kw.update(width=width, height=height)br: BuildResult = rt.build(ws, **kw)ws.write_json(ws.artifacts / "build_last.json", br)if not br.ok:- return text_observation(build_failure_lines(br, ws.root, warns, tail_n=_STDERR_TAIL_LINES), ok=False, limit=3000,- numbers={"stage": "build", "error_type": br.error_type, "error_file": br.error_file,- "error_line": br.error_line}), br, warns+ return _build_failed(ctx, br, warns), br, warnsreturn None, br, warns@@ -586,7 +610,7 @@ def gl_probe(ctx: ToolContext, args: GlProbeArgs) -> Observation:frames = sorted(Path(br.extra_paths["frames"]).glob("f*_t*.png")) if br.extra_paths.get("frames") else []lines = [f"PROBE OK ({br.duration_ms} ms, {br.census.get('renderer', 'GL')}) — frame at t={args.t:g}s", text]if warns:- lines.append("lint warnings:\n" + "\n".join(warns[:8]))+ lines.append("lint warnings:\n" + "\n".join(warns[:_LINT_WARNS_SHOWN]))numbers.update({"stage": "probe", "t": args.t, "duration_ms": br.duration_ms})return text_observation(lines, ok=numbers.get("gate_errors", 0) == 0, numbers=numbers,images=[str(p) for p in frames[:1]], limit=3000)@@ -613,12 +637,12 @@ def gl_frames(ctx: ToolContext, args: GlFramesArgs) -> Observation:images.append(str(dst))lines = [f"FRAMES OK ({br.duration_ms} ms, {br.census.get('renderer', 'GL')}) — sheet tiles labelled t=<s>; compare them for motion", text]if warns:- lines.append("lint warnings:\n" + "\n".join(warns[:8]))+ lines.append("lint warnings:\n" + "\n".join(warns[:_LINT_WARNS_SHOWN]))numbers.update({"stage": "frames", "times": args.times, "duration_ms": br.duration_ms, "sheet": rel_path(images[0], ctx.workspace.root) if images else ""})return text_observation(lines, ok=numbers.get("gate_errors", 0) == 0, numbers=numbers, images=images, limit=3000)-# ===================================================================== tools_texture+# ===================================================================== texturing_OBJECT_TRACKS = (Track.STATIC_OBJECT.value, Track.ARTICULATED_OBJECT.value)@@ -686,8 +710,6 @@ class TexturePreviewArgs(BaseModel):"Render artifacts/object_textured.glb (after texture_pass) as a labelled contact sheet + list the generated textures.",tracks=_OBJECT_TRACKS, cost_hint="slow")def texture_preview(ctx: ToolContext, args: TexturePreviewArgs) -> Observation:- from codeverse.spatial.tool_common import cached_render_glb, resolve_views-ws = ctx.workspaceglb = ws.artifacts / "object_textured.glb"if not glb.is_file():@@ -701,7 +723,7 @@ def texture_preview(ctx: ToolContext, args: TexturePreviewArgs) -> Observation:return text_observation(text, numbers={"n_textures": len(pngs)}, images=images)-# ===================================================================== tools_reference+# ===================================================================== reference#: what the agent should compare, in the order that decides whether the object#: reads as the real thing (identity before polish)CHECKLIST = (@@ -747,12 +769,9 @@ def compare_reference(ctx: ToolContext, args: CompareReferenceArgs) -> Observati("outline: red=reference only, blue=yours", diff_png)],out_dir / f"compare_reference_{args.view}_ref{args.reference_index}.png", cols=3, tile=384)iou = float(res["iou"])- verdict = "good match" if iou >= 0.8 else "rough match" if iou >= 0.6 else "POOR match"- if not res["reliable"]:- verdict += " (IoU UNRELIABLE: background mask failed — trust the pictures, not the number)"lines = [f"REFERENCE #{args.reference_index} ({ref_path.name}, role={ref.get('role', 'target')}) vs your {args.view} "- f"render: outline IoU {iou:.2f} → {verdict}; aspect w/h yours {res['render_aspect']:.2f} vs reference "+ f"render: outline IoU {iou:.2f} → {_iou_verdict(res)}; aspect w/h yours {res['render_aspect']:.2f} vs reference "f"{res['ref_aspect']:.2f} (err {res['aspect_ratio_err']:.0%}).",f"Look at the sheet and check, in this order: {CHECKLIST}",]diff --git a/harness/codeverse/spatial/turntable.py b/harness/codeverse/spatial/turntable.pydeleted file mode 100644index 61d8b419..00000000--- a/harness/codeverse/spatial/turntable.py+++ /dev/null@@ -1,43 +0,0 @@-"""Assemble rendered frames into a turntable video (ffmpeg) or animated GIF (PIL)."""--from __future__ import annotations--import shutil-import subprocess-from pathlib import Path--from codeverse.config import get_settings-from codeverse.spatial.sheet import write_gif---def assemble_turntable(frames: list[Path], out: Path, *, fps: int = 12) -> Path:- """Write ``out`` from ``frames``; ``.mp4`` needs ffmpeg (else falls back to ``.gif``)."""- if not frames:- raise ValueError("assemble_turntable: no frames")- out = Path(out)- out.parent.mkdir(parents=True, exist_ok=True)- ffmpeg = get_settings().binaries.ffmpeg- if out.suffix.lower() == ".mp4" and shutil.which(ffmpeg):- return _mp4(frames, out, fps, ffmpeg)- if out.suffix.lower() == ".mp4":- out = out.with_suffix(".gif")- return _gif(frames, out, fps)---def _mp4(frames: list[Path], out: Path, fps: int, ffmpeg: str) -> Path:- listing = out.parent / f".{out.stem}_frames.txt"- listing.write_text("".join(f"file '{f.resolve()}'\nduration {1 / fps:.4f}\n" for f in frames))- cmd = [- ffmpeg, "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", str(listing),- "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2,format=yuv420p", "-r", str(fps), "-c:v", "libx264", "-crf", "22", str(out),- ]- proc = subprocess.run(cmd, capture_output=True, text=True, timeout=300)- listing.unlink(missing_ok=True)- if proc.returncode != 0 or not out.is_file():- raise RuntimeError(f"ffmpeg failed ({proc.returncode}): {proc.stderr[-1500:]}")- return out---def _gif(frames: list[Path], out: Path, fps: int) -> Path:- """Animated GIF via the shared writer (``spatial.sheet.write_gif``)."""- return write_gif(frames, out, fps=fps)diff --git a/harness/runtime_js/export_glb.mjs b/harness/runtime_js/export_glb.mjsindex d7a35eae..5790ebbc 100644--- a/harness/runtime_js/export_glb.mjs+++ b/harness/runtime_js/export_glb.mjs@@ -20,9 +20,9 @@import fs from 'node:fs';import path from 'node:path';-import { parseArgs } from 'node:util';import { pathToFileURL } from 'node:url';+import { finish, parseCli } from './lib/cli.mjs';import { installExporterPolyfills } from './lib/node_polyfills.mjs';import { objectCensus, findNonFinitePositions, worldBox } from './lib/census.mjs';import { bakeInstancedMeshes, expandInstancedMesh } from './lib/instances.mjs';@@ -36,14 +36,9 @@ const TEXTURE_SLOTS = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emisconst PLACEMENT_THRESHOLD_M = 0.01;function cli() {- const { values } = parseArgs({- options: {- ws: { type: 'string' },- entry: { type: 'string', default: 'src/object.js' },- out: { type: 'string', default: 'artifacts/object.glb' },- census: { type: 'string', default: 'artifacts/census.json' },- normalise: { type: 'string', default: '0' },- },+ const values = parseCli({+ ws: {}, entry: { default: 'src/object.js' }, out: { default: 'artifacts/object.glb' },+ census: { default: 'artifacts/census.json' }, normalise: { default: '0' },});if (!values.ws) throw new Error('--ws <workspace dir> is required');const ws = path.resolve(values.ws);@@ -57,10 +52,6 @@ function cli() {};}-function emit(obj) {- process.stdout.write(JSON.stringify(obj) + '\n');-}-/** Capture console.warn/error from three (e.g. unsupported materials) as warnings. */function captureWarnings(sink) {const origWarn = console.warn;@@ -78,7 +69,7 @@ function captureWarnings(sink) {async function loadBuild(entry) {if (!fs.existsSync(entry)) {const e = new Error(`entry module not found: ${entry}`);- e.name = 'MissingEntry';+ e.name = 'MissingEntryFile'; // same spelling as every python runtime's build.jsonthrow e;}const mod = await import(pathToFileURL(entry).href);@@ -240,7 +231,7 @@ async function main() {fs.mkdirSync(path.dirname(args.census), { recursive: true });fs.writeFileSync(args.census, JSON.stringify(census, null, 2));- emit({ ok: true, glb: args.out, census: args.census, duration_ms: Date.now() - t0,+ finish({ ok: true, glb: args.out, census: args.census, duration_ms: Date.now() - t0,tri_count: census.tri_count, parts: census.parts.length, warnings });}@@ -265,6 +256,5 @@ main().catch((err) => {} catch (_e) {/* reporting must never mask the original failure */}- emit(record);- process.exit(1);+ finish(record, 1);});diff --git a/harness/runtime_js/lib/host_compile.mjs b/harness/runtime_js/lib/host_compile.mjsindex 34af4ded..db5f140a 100644--- a/harness/runtime_js/lib/host_compile.mjs+++ b/harness/runtime_js/lib/host_compile.mjs@@ -2,12 +2,9 @@* Compile-time material machinery (page-side): capture the FINAL GLSL sources* of every custom material (ShaderMaterial directly; onBeforeCompile via a* cache-key-preserving wrapper), attribute compiler errors to materials by- * source-line match, audit runtime materials (fog/uTime), and swap custom- * shaders for plain ones for the counterfactual presence probe.+ * source-line match, audit runtime materials (fog/uTime).*/-import { isCustomShader } from './host_census.mjs';-export const captured = []; // {name, type, vs, fs} final shader sources per custom materialexport function captureMaterialSources(scene, THREE) {@@ -70,40 +67,3 @@ export function materialAudit(scene, THREE) {});return out;}----/**- * Counterfactual: swap custom-shader materials for plain ones (ShaderMaterial →- * grey MeshStandardMaterial, onBeforeCompile → unpatched clone). Returns an- * undo function. Used by the shader-presence probe (pixel diff vs normal).- */-export function stripCustomShaders(scene, THREE) {- const undo = [];- const cloneCache = new Map();- scene.traverse((o) => {- if (!o.material) return;- const mats = Array.isArray(o.material) ? o.material : [o.material];- const swapped = mats.map((m) => {- if (!m || !isCustomShader(m, THREE)) return m;- if (cloneCache.has(m.uuid)) return cloneCache.get(m.uuid);- let rep;- if (m.isShaderMaterial || m.isRawShaderMaterial) {- rep = new THREE.MeshStandardMaterial({ color: 0x808080, roughness: 0.8, side: m.side, transparent: m.transparent, opacity: m.opacity, depthWrite: m.depthWrite });- } else {- rep = m.clone();- delete rep.onBeforeCompile; // clone() does not copy the own patch, but be explicit- rep.customProgramCacheKey = THREE.Material.prototype.customProgramCacheKey;- }- cloneCache.set(m.uuid, rep);- return rep;- });- if (swapped.some((m, i) => m !== mats[i])) {- const orig = o.material;- o.material = Array.isArray(orig) ? swapped : swapped[0];- undo.push(() => { o.material = orig; });- }- });- return () => { for (const u of undo) u(); for (const m of cloneCache.values()) m.dispose(); };-}-diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjsindex 6044daf4..ce0b53ce 100644--- a/harness/runtime_js/lib/scene_host.mjs+++ b/harness/runtime_js/lib/scene_host.mjs@@ -19,7 +19,7 @@ import { placementTable } from './host_placement.mjs';import { frameStats, nearGeometry } from './host_metrics.mjs';import { frameCoverage } from './host_coverage.mjs';import { installShaderErrorHook } from './host_shader_errors.mjs';-import { attributeErrors, captured, captureMaterialSources, materialAudit, stripCustomShaders } from './host_compile.mjs';+import { attributeErrors, captured, captureMaterialSources, materialAudit } from './host_compile.mjs';import { makeRenderer, rendererString } from './browser/renderer.js';const FIXED_DT = 1 / 30;@@ -323,7 +323,7 @@ function renderOnce(cam) {}/** Render camera spec at time t; returns {dataUrl, ms}. */-function renderAt(spec, t, opts = {}) {+function renderAt(spec, t) {if (!state.booted) throw new Error('host not booted');advanceTo(t);state.scene.updateMatrixWorld(true);@@ -331,12 +331,10 @@ function renderAt(spec, t, opts = {}) {const t0 = performance.now();const savedFog = state.scene.fog;if (spec.noFog) state.scene.fog = null; // overview rig: structure over atmosphere- const undo = opts.stripCustom ? stripCustomShaders(state.scene, THREE) : null;try {renderOnce(cam);} finally {state.scene.fog = savedFog;- if (undo) undo();}const ms = Math.round(performance.now() - t0);return { dataUrl: state.canvas.toDataURL('image/png'), ms, sim_time: state.simTime };diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjsindex 66e8a91a..c37b5947 100644--- a/harness/runtime_js/render_scene.mjs+++ b/harness/runtime_js/render_scene.mjs@@ -24,7 +24,7 @@ const args = parseCli({times: { default: '0,1.5' }, width: { default: '1024' }, height: { default: '576' },gpu: { default: process.env.CV3D_RENDER_GPU || 'auto' }, 'fps-seconds': { default: '2' },'timeout-ms': { default: '240000' }, 'create-timeout-ms': { default: '' }, 'log-depth': { type: 'boolean', default: false },- 'orbit-fog': { type: 'boolean', default: false }, counterfactual: { type: 'boolean', default: false },+ 'orbit-fog': { type: 'boolean', default: false },});function tag(t) {@@ -105,12 +105,6 @@ async function main() {const file = `${c.name}_${tag(t)}.png`;dataUrlToPng(r.dataUrl, outFile(outDir, file));metrics.views.push({ name: c.name, kind: c.kind, path: file, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: r.ms });- if (args.counterfactual) {- const cf = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt, { stripCustom: true }), c, t);- const cfFile = `${c.name}_${tag(t)}_nocustom.png`;- dataUrlToPng(cf.dataUrl, outFile(outDir, cfFile));- metrics.views.push({ name: `${c.name}_nocustom`, kind: 'counterfactual', path: cfFile, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: cf.ms, counterfactual_of: file });- }} catch (e) { sceneErr(`render failed for '${c.name}' at t=${t}`, e); }}}diff --git a/harness/setup.sh b/harness/setup.shindex 4361199a..6f8690cf 100755--- a/harness/setup.sh+++ b/harness/setup.sh@@ -1,7 +1,7 @@#!/usr/bin/env bash# 3dcodeverse harness — idempotent installer / updater.#-# bash harness/scripts/setup.sh [options]+# bash harness/setup.sh [options]## Does, in order: version checks (python >= 3.10, node >= 20.6) -> `pip install -e# harness[<extras>]` -> `npm ci` in runtime_js *only when the lockfile moved* ->@@ -17,7 +17,7 @@ MIN_NODE_MAJOR=20 # node 20.6+ (`node --import` module hooks)MIN_NODE_MINOR=6HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-HARNESS="$(cd "$HERE/.." && pwd)"+HARNESS="$HERE"RUNTIME_JS="$HARNESS/runtime_js"PY="${PYTHON:-python3}"@@ -130,7 +130,6 @@ if command -v blender-5.0 >/dev/null 2>&1 || command -v blender >/dev/null 2>&1elseinfo "blender not found (optional: blender / urdf_blender tracks unavailable — docs/INSTALL.md §6)"fi-command -v ffmpeg >/dev/null 2>&1 && info "ffmpeg found" || info "ffmpeg not found (optional: turntables fall back to animated GIF)"# ------------------------------------------------------------------ python pkgif [ "$DO_PYTHON" -eq 1 ]; thendiff --git a/harness/tests/scene_gates/test_frame_motion.py b/harness/tests/scene_gates/test_frame_motion.pyindex e38ad33d..68439fdc 100644--- a/harness/tests/scene_gates/test_frame_motion.py+++ b/harness/tests/scene_gates/test_frame_motion.py@@ -88,11 +88,6 @@ def test_unmeasurable_views_are_skipped_not_called_static(tmp_path: Path) -> Nonassert motion_from_dir(tmp_path / "nowhere") == []-def test_counterfactual_views_never_count(tmp_path: Path) -> None:- m = _metrics(tmp_path, ("Establishing_nocustom", "counterfactual", int(0.9 * W * H), 60))- assert motion_rows(m, tmp_path) == []--def test_frame_gate_reports_motion_as_info_and_freeze_as_error(tmp_path: Path) -> None:moving = _metrics(tmp_path, ("Establishing", "authored", int(0.05 * W * H), 40))moving["motion"] = [r.as_dict() for r in motion_rows(moving, tmp_path)]diff --git a/harness/tests/scene_gates/test_judge_views.py b/harness/tests/scene_gates/test_judge_views.pyindex 8e9dc2e6..628cdcb8 100644--- a/harness/tests/scene_gates/test_judge_views.py+++ b/harness/tests/scene_gates/test_judge_views.py@@ -37,9 +37,8 @@ def test_default_selection_is_authored_plus_overviews():assert len(rs.views) == 18 and sel.contact_sheet == rs.contact_sheet-def test_small_sets_pass_through_and_nocustom_dropped():+def test_small_sets_pass_through():rs = _rs(times=(0.0,), orbit=False)- rs.views.append(RenderView(name="Establishing_nocustom", path="/x/cf.png", time_s=0.0))sel = select_judge_views(rs, max_n=10)assert [v.name for v in sel.views] == AUTHOREDassert select_judge_views(RenderSet(), max_n=10).views == []diff --git a/harness/tests/scene_runtime/test_probes.py b/harness/tests/scene_runtime/test_probes.pyindex 30edbbc1..78c0a729 100644--- a/harness/tests/scene_runtime/test_probes.py+++ b/harness/tests/scene_runtime/test_probes.py@@ -1,11 +1,11 @@-"""Browser-backed probes: scene probe, shader preflight, shader presence."""+"""Browser-backed probes: scene probe, shader preflight."""from __future__ import annotationsimport pytestfrom codeverse.contracts.artifacts import Severity-from codeverse.spatial.probes import check_shaders, probe_scene, shader_presence+from codeverse.spatial.probes import check_shaders, probe_scenefrom tests.scene_runtime.conftest import needs_browserpytestmark = [pytest.mark.node, needs_browser]@@ -120,24 +120,8 @@ def test_check_shaders_static_audit_without_compile(starter_ws):assert any(f.target == "src/shaders/bad.js:2" for f in rep.errors)-def test_shader_presence_on_example_and_when_hidden(starter_ws):- obs = shader_presence(starter_ws)- assert obs.ok and obs.numbers["custom_materials"] == 2- assert obs.numbers["max_diff_frac"] > 0.05 and "PRESENT" in obs.text- assert len(obs.images) >= 2- # hide the custom-shader meshes → stripping changes nothing- p = starter_ws.src / "zones" / "pondside.js"- p.write_text(p.read_text().replace(" water.name = 'PondWater';", " water.name = 'PondWater';\n water.visible = false;"))- e = starter_ws.src / "env.js"- e.write_text(e.read_text().replace(" sky.name = 'Sky';", " sky.name = 'Sky';\n sky.visible = false;"))- obs2 = shader_presence(starter_ws)- assert obs2.numbers["max_diff_frac"] == 0.0 and "NOT VISIBLE" in obs2.text--def test_probe_scene_hanging_create_scene_times_out_as_agent_finding(starter_ws):- """Finding: a createScene that never resolves (loader.load without onError on a- missing asset) must time out INSIDE boot with an agent-attributed finding, not- hang into the driver watchdog (exit 3 → 'harness failure, not your code')."""+ """A hanging createScene times out as an agent finding, not a harness crash."""(starter_ws.src / "scene.js").write_text("import * as THREE from 'three';\n""export async function createScene({ THREE: T, renderer, loaders }) {\n"@@ -157,8 +141,7 @@ def test_probe_scene_hanging_create_scene_times_out_as_agent_finding(starter_ws)def test_probe_result_tool_semantics(starter_ws, monkeypatch):- """SceneProbeResult.ok/errors = 'did the tool run' (MCP is_error); agent-fixable- gate findings live in .findings and never mark the tool call as failed."""+ """Tool success is distinct from agent-fixable gate success."""import codeverse.spatial.probes as probes_modfrom codeverse.spatial.render_scene import NodeResult, SceneRenderErrordiff --git a/harness/tests/scene_runtime/test_runtime.py b/harness/tests/scene_runtime/test_runtime.pyindex 68cbe30a..da2a9462 100644--- a/harness/tests/scene_runtime/test_runtime.py+++ b/harness/tests/scene_runtime/test_runtime.py@@ -10,10 +10,11 @@ from codeverse.contracts.common import Languagefrom codeverse.languages import get_runtimefrom codeverse.languages.base import LanguageRuntimefrom codeverse.languages.scene_threejs import SceneThreeJsRuntime+from codeverse.prompts import PROMPTS_DIRfrom tests.scene_runtime.conftest import needs_browser-def test_runtime_registered_and_conforms():+def test_runtime_registered_conforms_and_writes_skeleton(ws):rt = get_runtime(Language.SCENE_THREEJS)assert isinstance(rt, SceneThreeJsRuntime)assert isinstance(rt, LanguageRuntime)@@ -21,16 +22,7 @@ def test_runtime_registered_and_conforms():assert "src/scene.js" in rt.entry_globs and "src/zones/*.js" in rt.entry_globsdoc = rt.contract_doc()assert "createScene" in doc and "update(t, dt)" in doc- # the GLSL chunk rules are the cookbook's job, not the contract's — this used to- # assert them against languages/scene_threejs/CONTRACT.md, a file contract_doc()- # never reached (deleted 2026-08-28); prompts/scene_threejs/glsl_cookbook.md states- # the same rule and IS delivered- assert "`#include <...>` alone on its line" in rt.cookbook_path().with_name("glsl_cookbook.md").read_text()- assert rt.cookbook_path().name == "cookbook.md"---def test_skeleton_writes_example(ws):- rt = SceneThreeJsRuntime()+ assert "`#include <...>` alone on its line" in (PROMPTS_DIR / rt.prompt_dir / "glsl_cookbook.md").read_text()paths = rt.skeleton(ws, None)assert (ws.src / "scene.js") in paths@@ -69,9 +61,7 @@ def test_build_fails_on_import_error(starter_ws):def test_build_interprets_combined_summary_offline(ws, monkeypatch):- """The single-boot build (probe_scene.mjs --compile) still yields the SAME two- GateReports: scene_probe from the probe summary, shader_preflight from the- embedded shader_report; a non-booting scene keeps the failed-empty shader gate."""+ """One probe boot yields both gate reports, including the no-boot shape."""import codeverse.languages.scene_threejs as rt_modfrom codeverse.spatial.render_scene import NodeResult@@ -119,9 +109,7 @@ def test_build_interprets_combined_summary_offline(ws, monkeypatch):def test_probe_crash_leaves_no_stale_probe_outputs(ws, monkeypatch):- """A driver crash (SceneRenderError) must not leave the previous round's census- or the root driver outputs (scene_probe.json / shader_preflight.json) looking- current; build.json on disk says ok:false, never the previous round's ok:true."""+ """A probe crash removes prior outputs and publishes a failed build."""import codeverse.spatial.render_scene as rs_modfrom codeverse.spatial.render_scene import SceneRenderErrordiff --git a/harness/tests/spatial_tools/test_complexity.py b/harness/tests/spatial_tools/test_complexity.pyindex 7161d928..328e2425 100644--- a/harness/tests/spatial_tools/test_complexity.py+++ b/harness/tests/spatial_tools/test_complexity.py@@ -16,7 +16,6 @@ from codeverse.spatial.complexity import (band_of,complexity_of_glb,complexity_of_parts,- complexity_summary_line,)from codeverse.spatial.measure import measure_glb, part_meshes@@ -73,7 +72,6 @@ def test_vector_shape_and_weights(stool_glb: Path) -> None:assert vec.index == pytest.approx(sum(COMPLEXITY_WEIGHTS[a] * v for a, v in vec.components.items()), abs=5e-4)- assert "complexity" in complexity_summary_line(vec)def test_detail_beats_primitives(tmp_path: Path) -> None:diff --git a/harness/tests/spatial_tools/test_connectivity.py b/harness/tests/spatial_tools/test_connectivity.pyindex 560777d0..62b5d944 100644--- a/harness/tests/spatial_tools/test_connectivity.py+++ b/harness/tests/spatial_tools/test_connectivity.py@@ -103,9 +103,9 @@ def test_missing_glb_is_error(tmp_path: Path) -> None:def test_pair_distance_sampled_fallback(monkeypatch: pytest.MonkeyPatch) -> None:- import codeverse.spatial.connectivity as c+ import codeverse.spatial.joints_collide as collide- monkeypatch.setattr(c, "_fcl_available", lambda: False)+ monkeypatch.setattr(collide, "_fcl", None)a = trimesh.creation.box(extents=(1, 1, 1))b = trimesh.creation.box(extents=(1, 1, 1))b.apply_translation((1.02, 0, 0))diff --git a/harness/tests/spatial_tools/test_render_common.py b/harness/tests/spatial_tools/test_render_common.pyindex b8a2469b..4dc68ff5 100644--- a/harness/tests/spatial_tools/test_render_common.py+++ b/harness/tests/spatial_tools/test_render_common.py@@ -42,16 +42,6 @@ def test_view_specs_is_the_one_camera_payload() -> None:assert json.loads(_views_json(SCENE_VIEWS)) == rc.view_specs(SCENE_VIEWS)-def test_read_json_never_raises(tmp_path: Path) -> None:- assert rc.read_json(tmp_path / "nope.json") == {}- bad = tmp_path / "bad.json"- bad.write_text("{not json")- assert rc.read_json(bad) == {}- good = tmp_path / "g.json"- good.write_text('{"a": 1}')- assert rc.read_json(good) == {"a": 1}--def test_build_sheet_uses_the_settings_grid_and_guards_empty(tmp_path: Path) -> None:assert rc.build_sheet([], tmp_path / "none.png") is Nonefor i in range(2):@@ -97,19 +87,6 @@ def test_gl_contact_sheet_and_gif_go_through_the_shared_writers(tmp_path: Path)assert write_gif(frames[:1], tmp_path / "one.gif") is None # < 2 frames = no preview-def test_turntable_gif_uses_the_same_writer(tmp_path: Path) -> None:- from codeverse.spatial.turntable import assemble_turntable-- paths = []- for i in range(4):- p = tmp_path / f"tt{i}.png"- Image.new("RGB", (64, 64), (10 * i, 0, 0)).save(p)- paths.append(p)- out = assemble_turntable(paths, tmp_path / "tt.gif", fps=8)- with Image.open(out) as im:- assert im.n_frames == 4 and im.width == 64--# --------------------------------------------------------------------------- parts loaderdef test_solid_parts_is_cached_parts_without_the_empty_ones(stool_glb: Path) -> None:from codeverse.spatial.measure import cached_parts, solid_parts@@ -121,11 +98,10 @@ def test_solid_parts_is_cached_parts_without_the_empty_ones(stool_glb: Path) ->def test_shared_number_formatters() -> None:from codeverse.spatial.connectivity import _fmt_vec as conn_vec- from codeverse.spatial.contract import _fmt_ext, _fmt_vecfrom codeverse.spatial.measure import fmt_extent_cm, fmt_vec- assert _fmt_ext is fmt_extent_cm and fmt_extent_cm([0.34, 0.47]) == "34.0×47.0"- assert _fmt_vec([-0.00001, 0.5, 0]) == "(+0.000, +0.500, +0.000)" # never '-0.000'+ assert fmt_extent_cm([0.34, 0.47]) == "34.0×47.0"+ assert fmt_vec([-0.00001, 0.5, 0]) == "(+0.000, +0.500, +0.000)" # never '-0.000'assert conn_vec((-0.00001, 0.5, 0.0)) == "(+0.0000, +0.5000, +0.0000)" # 4 decimals, same shapeassert fmt_vec([1.23456], digits=2) == "(+1.23)"@@ -153,12 +129,9 @@ def test_tool_unavailable_is_reported_by_the_registry(stool_ctx: ToolContext, momonkeypatch.setattr(tc, "lazy", boom)monkeypatch.setattr("codeverse.spatial.tools.lazy", boom)- monkeypatch.setattr("codeverse.spatial.tools.lazy", boom)- monkeypatch.setattr("codeverse.spatial.tools.lazy", boom)- monkeypatch.setattr("codeverse.spatial.tools.lazy", boom)ws = stool_ctx.workspace(ws.artifacts / "object_textured.glb").write_bytes((ws.artifacts / "object.glb").read_bytes())- for name in ("build", "render_views", "scene_probe", "texture_preview"):+ for name in ("build", "render_views", "texture_preview"):obs = get_tool(name).call(stool_ctx, {})assert not obs.ok and obs.text.startswith(f"tool {name} unavailable:"), (name, obs.text)# a graphics workspace: the gl tools degrade the same waydiff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.pyindex ffa6f588..0c71efb3 100644--- a/harness/tests/spatial_tools/test_tools.py+++ b/harness/tests/spatial_tools/test_tools.py@@ -41,10 +41,14 @@ def test_registry_has_every_tool() -> None:f"missing {sorted(EXPECTED_TOOLS - registered)} — update CORE_TOOLS/SCOPED_TOOLS above")static_blender = {t.name for t in list_tools(track="static_object", language="blender")}assert "joint_sweep" not in static_blender and "gl_probe" not in static_blender- assert "texture_pass" in static_blender- assert "shader_probe" in {t.name for t in list_tools(track="scene", language="scene_threejs")}+ assert {"texture_pass", "texture_preview"} <= static_blender+ scene = {t.name for t in list_tools(track="scene", language="scene_threejs")}+ assert "shader_probe" in scene+ assert not {"texture_pass", "texture_preview"} & {t.name for t in list_tools(track="scene")}graphics = {t.name for t in list_tools(track="graphics", language="glsl_shader")}assert {"gl_probe", "gl_frames"} <= graphics and "texture_pass" not in graphics and "scene_probe" not in graphics+ texture_card = get_tool("texture_pass").card()+ assert "judge" in texture_card and "texture_pass" in texture_cardfor t in list_tools():assert t.schema()["type"] == "object" and t.description@@ -226,6 +230,25 @@ def test_render_views_cached(stool_ctx: ToolContext, fake_renderer) -> None:assert not obs.ok and "front_right_34" in obs.textobs = get_tool("render_views").call(stool_ctx, {"mode": "xray"})assert not obs.ok and "shaded" in obs.text+ # 'depth' was advertised from the first commit and never drawn by any renderer:+ # a usage error with the mode list, not a RenderError from deep inside the rig+ obs = get_tool("render_views").call(stool_ctx, {"mode": "depth"})+ assert not obs.ok and "shaded" in obs.text and "failed" not in obs.text+++def test_render_modes_match_the_js_rig() -> None:+ """One mode tuple: contracts.RENDER_MODES ↔ runtime_js/render_glb.mjs MODES ↔ the arg schema."""+ import re++ from codeverse.config import get_settings+ from codeverse.contracts.artifacts import RENDER_MODES++ src = (get_settings().runtime_js_dir() / "render_glb.mjs").read_text()+ m = re.search(r"const MODES = \[([^\]]*)\]", src)+ assert m and tuple(re.findall(r"'([a-z]+)'", m.group(1))) == RENDER_MODES+ assert "depth" not in RENDER_MODES+ for name in ("render_views", "render_sheet"):+ assert get_tool(name).schema()["properties"]["mode"]["description"] == " | ".join(RENDER_MODES)def test_render_sheet_and_isolate(stool_ctx: ToolContext, fake_renderer) -> None:@@ -253,7 +276,9 @@ def test_compare_silhouette_tool(stool_ctx: ToolContext, fake_renderer) -> None:assert not obs.ok and "out of range" in obs.text-def test_scene_tools_degrade_when_unavailable(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:+def test_texture_tools_degrade_when_texturing_is_unavailable(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:+ """`lazy` guards only the optional siblings (codeverse.languages / codeverse.texturing);+ spatial-on-spatial imports are ordinary imports since 2026-08-29."""import codeverse.spatial.tool_common as tcimport codeverse.spatial.tools as ts@@ -261,37 +286,36 @@ def test_scene_tools_degrade_when_unavailable(stool_ctx: ToolContext, monkeypatcraise tc.ToolUnavailable(f"{module} not importable")monkeypatch.setattr(ts, "lazy", boom)- for name in ("joint_sweep", "shader_probe", "scene_probe", "scene_views"):- obs = get_tool(name).call(stool_ctx, {})- assert not obs.ok and obs.text.startswith(f"tool {name} unavailable:"), name+ stool_ctx.workspace.write_json(stool_ctx.workspace.plan_path, _stool_plan_with_missing_backrest())+ obs = get_tool("texture_pass").call(stool_ctx, {})+ assert not obs.ok and obs.text.startswith("tool texture_pass unavailable:"), obs.textdef test_scene_tools_with_fake_siblings(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:import codeverse.spatial.tools as ts-- calls = {}+ from codeverse.spatial.probes import SceneProbeResultdef fake_check_shaders(ws, *, module=None, timeout_s=90.0):return GateReport(gate="shaders", passed=False, findings=[GateFinding(gate="shaders", severity=Severity.ERROR, target="src/shaders/water.js", message="ERROR: 0:12: 'vUv' undeclared", fix_hint="declare varying vec2 vUv")])- def fake_probe_scene(ws, **kw):- return {"census": {"meshes": 12, "lights": 2}, "fps": 58.0, "errors": []}-- def fake_joint_sweep(ws, *, n_random=8, seed=0, render=True, out_dir=None, joint=None, expected_direction=None, joints=None):- calls["n_random"], calls["joint"] = n_random, joint- from codeverse.spatial.registry import Observation- return Observation(ok=True, text="sweep ok", numbers={"poses": n_random})+ failed = GateReport(gate="scene_probe", passed=False, findings=[+ GateFinding(gate="scene_probe", severity=Severity.ERROR, target="src/scene.js", message="console: boom")])- def fake_lazy(module, attr):- return {"check_shaders": fake_check_shaders, "probe_scene": fake_probe_scene, "joint_sweep_observation": fake_joint_sweep}[attr]+ def fake_probe_scene(ws, **kw):+ return SceneProbeResult(gate=failed, census={"meshes": 12, "lights": 2}, ok=True, findings=["[error] src/scene.js: console: boom"])- monkeypatch.setattr(ts, "lazy", fake_lazy)+ monkeypatch.setattr(ts, "check_shaders", fake_check_shaders)+ monkeypatch.setattr(ts, "probe_scene", fake_probe_scene)obs = get_tool("shader_probe").call(stool_ctx, {})assert not obs.ok and "vUv" in obs.text and "declare varying" in obs.textobs = get_tool("scene_probe").call(stool_ctx, {})- assert obs.ok and "meshes=12" in obs.text and obs.numbers["fps"] == 58.0- obs = get_tool("joint_sweep").call(stool_ctx, {"joints": ["hinge"], "n_samples": 5})- assert obs.ok and calls == {"n_random": 5, "joint": "hinge"}+ # ok = the probe TOOL ran; the failed gate is a result, not a tool error (SceneProbeResult)+ assert obs.ok and "meshes=12" in obs.text and "boom" in obs.text and obs.numbers["census"]["meshes"] == 12+ monkeypatch.setattr(ts, "probe_scene", lambda ws, **kw: SceneProbeResult(gate=failed, errors=["driver died"], ok=False))+ obs = get_tool("scene_probe").call(stool_ctx, {})+ assert not obs.ok and "driver died" in obs.text+ obs = get_tool("joint_sweep").call(stool_ctx, {})+ assert not obs.ok and "run `build`" in obs.text # no robot.urdf in a static workspace# --------------------------------------------------------------------------- build without a GLB (scene / graphics)@@ -412,11 +436,12 @@ def test_build_card_and_observation_are_unchanged_when_fewer_turns_is_off(stool_assert "CONNECTIVITY" not in obs.text and "CONTRACT" not in obs.text and "CHECKS:" not in obs.textassert "checks_passed" not in obs.numberscard_off = get_tool("build").card()+ description = get_tool("build").descriptionassert "check_connectivity" not in card_offmonkeypatch.setenv("CV3D_FEWER_TURNS", "1")card_on = get_tool("build").card()assert "do not call those two tools separately" in card_on and card_on.startswith(card_off.splitlines()[0][:40])- assert get_tool("build").description == get_tool("build").description # the static text never changes+ assert get_tool("build").description == description # the static text never changesdef test_a_failed_build_tells_the_agent_WHY_not_to_build_again(tmp_ws):diff --git a/harness/tests/threejs_render/test_render.py b/harness/tests/threejs_render/test_render.pyindex 53cf8180..3bded368 100644--- a/harness/tests/threejs_render/test_render.py+++ b/harness/tests/threejs_render/test_render.py@@ -1,4 +1,4 @@-"""render_glb / render_turntable (node + headless Chrome) and offline guards."""+"""render_glb (node + headless Chrome) and offline guards."""from __future__ import annotations@@ -10,7 +10,7 @@ from PIL import Imagefrom codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPresetfrom codeverse.spatial import render as render_mod-from codeverse.spatial.render import RenderError, render_glb, render_turntable+from codeverse.spatial.render import RenderError, render_glbdef test_render_glb_offline_validation(tmp_path: Path):@@ -77,11 +77,3 @@ def test_render_views_modes_isolate_and_cache(stool_glb: Path, tmp_path: Path):ex = render_glb(stool_glb, tmp_path / "explode", views=[ViewPreset("front", 0, 8)], explode=0.5, mode="clay", width=128, height=128, sheet=False)assert Path(ex.views[0].path).is_file()---def test_render_turntable_gif(stool_glb: Path, tmp_path: Path):- out = render_turntable(stool_glb, tmp_path / "tt.gif", n=6, width=96, height=96)- assert out.suffix == ".gif" and out.is_file()- with Image.open(out) as im:- assert getattr(im, "n_frames", 1) == 6diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.pyindex 61f304bc..11bc9727 100644--- a/harness/tests/threejs_render/test_runtime_js.py+++ b/harness/tests/threejs_render/test_runtime_js.py@@ -31,20 +31,12 @@ def test_export_cli_writes_census_and_error_json(stool_ws: Workspace, tmp_path:with pytest.raises(NodeError) as ei:run_node(rt / "export_glb.mjs", ["--ws", str(stool_ws.root), "--entry", "src/nope.js"], three_hook=True, timeout_s=60)err = ei.value.result.last_json["error"]- assert err["type"] == "MissingEntry"+ assert err["type"] == "MissingEntryFile"assert (stool_ws.artifacts / "export_error.json").is_file()-def test_render_glb_driver_protocol_and_shared_plumbing(tmp_path: Path):- """render_glb.mjs is a thin entry: shared arg parsing / JSON-last-line- protocol (lib/cli.mjs), shared browser + static server (lib/host_env.mjs),- shared release dance (lib/host_page.mjs) — and it still reports a failure as- exit 1 with `{ok: false, error}` as the LAST stdout line."""+def test_render_glb_driver_reports_invalid_requests_as_last_json(tmp_path: Path):rt = runtime_js_dir()- src = (rt / "render_glb.mjs").read_text()- assert "from './lib/cli.mjs'" in src and "from './lib/host_env.mjs'" in src- assert "releaseBrowser" in src- assert "createRequire" not in src and "parseArgs" not in src # no second copy of eitherwith pytest.raises(NodeError) as ei:run_node(rt / "render_glb.mjs",["--glb", str(tmp_path / "missing.glb"), "--out", str(tmp_path / "out"),diff --git a/harness/tests/threejs_render/test_skeleton.py b/harness/tests/threejs_render/test_skeleton.pyindex 0c2a71e9..999a1173 100644--- a/harness/tests/threejs_render/test_skeleton.py+++ b/harness/tests/threejs_render/test_skeleton.py@@ -53,7 +53,6 @@ def test_runtime_protocol_surface():assert rt.entry_globs == ("src/object.js", "src/parts/*.js")doc = rt.contract_doc()assert "build" in doc and "three" in doc.lower()- assert rt.cookbook_path().name == "cookbook.md"def test_skeleton_rejects_non_static_plan(tmp_path: Path):diff --git a/harness/tests/threejs_render/test_stale_outputs.py b/harness/tests/threejs_render/test_stale_outputs.pyindex aa68e979..9d2b7a52 100644--- a/harness/tests/threejs_render/test_stale_outputs.py+++ b/harness/tests/threejs_render/test_stale_outputs.py@@ -49,6 +49,6 @@ def test_node_failure_with_result_writes_failed_build_json(tmp_path, monkeypatchmonkeypatch.setattr(rt_mod, "run_node", timeout)res = ThreeJsRuntime().build(ws)- assert not res.ok and res.error_type == "Timeout"+ assert not res.ok and res.error_type == "BuildTimeout"assert not (ws.artifacts / "object.glb").exists()assert json.loads((ws.artifacts / "build.json").read_text())["ok"] is Falsediff --git a/harness/tests/urdf_joints/test_export.py b/harness/tests/urdf_joints/test_export.pyindex 8cd67c9b..8dd257b5 100644--- a/harness/tests/urdf_joints/test_export.py+++ b/harness/tests/urdf_joints/test_export.py@@ -52,7 +52,9 @@ def test_urdf_to_glb_hierarchy_and_extras(tmp_path):assert _gltf_json(glb2)["scenes"][0]["extras"]["pose"] == {"hinge": 1.57}-def test_render_poses_with_fake_renderer_builds_sheet(tmp_path):+def test_render_poses_with_fake_renderer_builds_sheet(tmp_path, monkeypatch):+ import codeverse.spatial.joints_export as je+urdf, meshes = write_mesh_robot(tmp_path)r = load_urdf(urdf, meshes)calls = []@@ -67,7 +69,8 @@ def test_render_poses_with_fake_renderer_builds_sheet(tmp_path):rs.views.append(RenderView(name=v.name, path=str(p)))return rs- out = render_poses(r, tmp_path / "ren", renderer=fake_renderer)+ monkeypatch.setattr(je, "render_glb", fake_renderer)+ out = render_poses(r, tmp_path / "ren")assert [label for label, _ in out] == ["rest", "hinge@upper"]assert len(calls) == 2 and all(c.exists() for c in calls)sheet = tmp_path / "ren" / ARTICULATION_SHEET_NAME@@ -95,17 +98,31 @@ def test_multi_material_link_keeps_materials(tmp_path):assert sorted(n for n in [e[1] for e in s.graph.to_edgelist()] if n.startswith("body")) == ["body", "body__0", "body__1"]-def test_joint_sweep_observation_offline(tmp_path):- from codeverse.spatial.joints import joint_sweep_observation+def test_joint_sweep_tool_offline(tmp_path, monkeypatch):+ """The ``joint_sweep`` tool body lives in spatial.tools: collision sweep over every+ joint, renders narrowed to ``joints`` (+ rest) through ``render_poses``."""+ import codeverse.spatial.tools as ts+ from codeverse.spatial.registry import ToolContext, get_toolfrom codeverse.workspace import Workspace- from tests.urdf_joints.conftest import write_mesh_robotws = Workspace(tmp_path / "ws").create()- obs = joint_sweep_observation(ws, render=False)+ ctx = ToolContext(workspace=ws, language="urdf_blender", track="articulated_object")+ obs = get_tool("joint_sweep").call(ctx, {})assert not obs.ok and "run `build`" in obs.textwrite_mesh_robot(ws.artifacts)- obs = joint_sweep_observation(ws, render=False, joint="hinge", expected_direction="front")- assert obs.ok and obs.numbers["max_penetration_m"] == 0.0 and obs.numbers["motion_check"]["ok"]+ rendered: list[list[str] | None] = []++ def fake_render_poses(robot, out_dir, poses=None, **kw):+ rendered.append(None if poses is None else [label for label, _ in poses])+ Image.new("RGB", (8, 8), "gray").save(out_dir / ARTICULATION_SHEET_NAME)+ return []++ monkeypatch.setattr(ts, "render_poses", fake_render_poses)+ obs = get_tool("joint_sweep").call(ctx, {"joints": ["hinge"], "n_samples": 5})+ assert obs.ok and obs.numbers["max_penetration_m"] == 0.0+ assert rendered == [["rest", "hinge@upper"]] and obs.images[0].endswith(ARTICULATION_SHEET_NAME) # lower=0 dedupes into rest+ obs = get_tool("joint_sweep").call(ctx, {})+ assert rendered[-1] is None # empty joints = the full sheet (render_poses default)def test_robot_named_like_a_link_keeps_frame_and_placement(tmp_path):diff --git a/harness/tests/urdf_joints/test_live_blender.py b/harness/tests/urdf_joints/test_live_blender.pyindex 92a81c74..dbed4272 100644--- a/harness/tests/urdf_joints/test_live_blender.py+++ b/harness/tests/urdf_joints/test_live_blender.py@@ -1,4 +1,4 @@-"""Real Blender builds (marked ``blender``): cabinet+door, drawer, bad pivot, yourdfpy, sheet."""+"""Real Blender builds (marked ``blender``): cabinet+door, drawer, bad pivot, yourdfpy."""from __future__ import annotations@@ -7,15 +7,7 @@ import pytestfrom codeverse.config import get_settingsfrom codeverse.languages.urdf import UrdfBlenderRuntime-from codeverse.spatial.joints import (- ARTICULATION_SHEET_NAME,- blender_render_glb,- fk,- link_world_meshes,- load_urdf,- motion_direction_check,- render_poses,-)+from codeverse.spatial.joints import fk, link_world_meshes, load_urdf, motion_direction_checkfrom codeverse.workspace import Workspacepytestmark = pytest.mark.blender@@ -82,7 +74,7 @@ def test_drawer_prismatic(tmp_path, drawer_plan):@needs_blender-def test_bad_pivot_is_caught_and_sheet_renders(tmp_path, cabinet_plan):+def test_bad_pivot_is_caught(tmp_path, cabinet_plan):ws = Workspace(tmp_path / "bad").create()rt = UrdfBlenderRuntime()rt.skeleton(ws, cabinet_plan)@@ -95,10 +87,6 @@ def test_bad_pivot_is_caught_and_sheet_renders(tmp_path, cabinet_plan):art = res.census["articulation"]assert art["summary"]["max_penetration_m"] > 0.05 and "hinge@upper" in art["summary"]["overlapping_poses"]assert any(f["severity"] == "error" and "body|door" in f["target"] for f in art["findings"])- r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")- out = render_poses(r, ws.artifacts / "renders" / "articulation", renderer=blender_render_glb)- assert [label for label, _ in out] == ["rest", "hinge@upper"]- assert (ws.artifacts / "renders" / "articulation" / ARTICULATION_SHEET_NAME).is_file()@needs_blenderdiff --git a/harness/tests/urdf_joints/test_runtime_offline.py b/harness/tests/urdf_joints/test_runtime_offline.pyindex 7f80cb36..d8c6744a 100644--- a/harness/tests/urdf_joints/test_runtime_offline.py+++ b/harness/tests/urdf_joints/test_runtime_offline.py@@ -64,7 +64,6 @@ def test_registry_and_contract():assert isinstance(rt, UrdfBlenderRuntime) and rt.entry_globs == ("src/model.py", "src/robot.urdf")doc = rt.contract_doc()assert "meshes/<link>.glb" in doc and "pivot" in doc- assert rt.cookbook_path().name == "cookbook.md"def test_build_ok(tmp_path, cabinet_plan, fake_blender):@@ -76,7 +75,7 @@ def test_build_ok(tmp_path, cabinet_plan, fake_blender):art = res.census["articulation"]assert art["summary"]["max_penetration_m"] == 0.0 and art["movable_joints"] == ["hinge"]assert res.census["links"]["door"]["islands"] == 1- assert res.stdout_tail == "built\n"+ assert res.stdout_tail == "built" # proc.tail joins lines: same shape as blender/cadquerydef test_build_lint_error_short_circuits(tmp_path, cabinet_plan, fake_blender):@@ -168,7 +167,7 @@ def test_build_timeout(tmp_path, cabinet_plan, fake_blender, monkeypatch):lambda *a, **k: ProcResult(returncode=-9, stdout="", stderr="", timed_out=True, duration_ms=0))ws = _ws(tmp_path, cabinet_plan)res = UrdfBlenderRuntime().build(ws, timeout_s=1)- assert not res.ok and res.error_type == "Timeout"+ assert not res.ok and res.error_type == "BuildTimeout"def test_wrapper_rejects_unsafe_link_names_offline():