Official Codebase of 3DCodeVerse
Python
articulated: deterministic repairs behind CV3D_ART_REPAIRS — reversed joint axes flipped in robot.urdf, buried links reported; transient renders retried once
ziyao4afa3187c1ae
diff --git a/harness/codeverse/spatial/render.py b/harness/codeverse/spatial/render.pyindex 27a4338b..48ccd2cf 100644--- a/harness/codeverse/spatial/render.py+++ b/harness/codeverse/spatial/render.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport hashlibimport json+import loggingimport osimport shutilimport time@@ -28,6 +29,9 @@ BACKGROUNDS = ("studio", "white", "transparent")CACHE_VERSION = 4 # bump when the rig changes in a way that invalidates cached PNGs+log = logging.getLogger(__name__)++class RenderError(RuntimeError):"""Rendering failed (node/puppeteer error, bad GLB, bad arguments)."""@@ -130,7 +134,17 @@ def render_glb(if use_cache and (cache_dir / "views.json").is_file():record = _restore_from_cache(cache_dir, out_dir)if record is None:- record = _run_render(glb, out_dir, params, gpu=gpu, timeout_s=timeout_s)+ try:+ record = _run_render(glb, out_dir, params, gpu=gpu, timeout_s=timeout_s)+ except RenderError as e:+ if not _transient(e):+ raise+ # compare_art_v4 (2026-08-28): under 12 concurrent cells the browser took 7.5 s to+ # open a page and the viewer's wait expired ("Waiting failed"); the cell lost its+ # in-loop judge for the round. One retry with twice the time is cheap next to that.+ log.warning("render_glb transient failure, retrying once with %.0f s: %s", timeout_s * 2, str(e)[:160])+ time.sleep(RETRY_PAUSE_S)+ record = _run_render(glb, out_dir, params, gpu=gpu, timeout_s=timeout_s * 2)if use_cache:_store_in_cache(cache_dir, out_dir, record)@@ -158,6 +172,16 @@ def render_glb()+#: render failures that are the box, not the model: a retry is worth one more timeout+TRANSIENT_MARKERS = ("waiting failed", "timed out", "timeout", "produced no result", "target closed", "session closed")+RETRY_PAUSE_S = 3.0+++def _transient(e: Exception) -> bool:+ text = str(e).lower()+ return any(m in text for m in TRANSIENT_MARKERS)++def _run_render(glb: Path, out_dir: Path, params: dict[str, Any], *, gpu: str, timeout_s: float) -> dict[str, Any]:args = ["--glb", str(glb), "--out", str(out_dir), "--views", json.dumps(params["views"]),diff --git a/harness/codeverse/tracks/articulated_object.py b/harness/codeverse/tracks/articulated_object.pyindex f31906af..412cb971 100644--- a/harness/codeverse/tracks/articulated_object.py+++ b/harness/codeverse/tracks/articulated_object.py@@ -26,6 +26,11 @@ from codeverse.contracts.common import TRACK_INFO, Trackfrom codeverse.contracts.plan import ArticulatedPlan, Planfrom codeverse.conventions import to_snakefrom codeverse.spatial.render import RenderError+from codeverse.tracks.articulated_repairs import (+ buried_links,+ repair_motion_directions,+ repairs_enabled,+)from codeverse.tracks.common import RunContextfrom codeverse.tracks.static_object import ObjectPipeline, StaticObjectTrackfrom codeverse.workspace import Workspace@@ -40,11 +45,16 @@ class ArticulatedPipeline(ObjectPipeline):def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:out = super().gates(ctx, round_index, build, measurement)+ # motion first: with CV3D_ART_REPAIRS a reversed joint is flipped in robot.urdf+ # before the sweep, so the pose sheet the judge sees shows the repaired motion+ motion = self._motion_gate(ctx)+ if motion is not None and motion.errors and repairs_enabled():+ motion = repair_motion_directions(ctx.ws, ctx.plan, motion, recheck=ctx.services.motion_checks,+ events=ctx.events)out_dir = ctx.ws.renders_dir(round_index) / "poses"report, views = ctx.services.joint_sweep(ctx.ws, ctx.plan, out_dir)ctx.extra["pose_views"] = viewsout.append(report)- motion = self._motion_gate(ctx)if motion is not None:out.append(motion)return out@@ -125,6 +135,11 @@ def default_joint_sweep(ws: Workspace, plan: Plan | None, out_dir: Path) -> tuplfix_hint="fix robot.urdf so every link has a mesh under meshes/<link>.glb and joints form one tree")]), []findings = [f.model_copy(update={"gate": SWEEP_GATE})for f in joints.aggregate_findings(joints.sweep_findings(report))]+ if repairs_enabled():+ try:+ findings += [f.model_copy(update={"gate": SWEEP_GATE}) for f in buried_links(robot)]+ except Exception as e: # noqa: BLE001 — an extra check never fails the gate+ log.warning("buried-link check failed: %s", e)gate = GateReport(gate=SWEEP_GATE, passed=not any(f.severity == Severity.ERROR for f in findings), findings=findings,duration_ms=int((time.time() - t0) * 1000))views: list[RenderView] = []diff --git a/harness/codeverse/tracks/articulated_repairs.py b/harness/codeverse/tracks/articulated_repairs.pynew file mode 100644index 00000000..b667525c--- /dev/null+++ b/harness/codeverse/tracks/articulated_repairs.py@@ -0,0 +1,188 @@+"""Deterministic repairs and checks for articulated builds (2026-08-29, phase 5).++Read from compare_art_v4 (14 prompts, 3 arms): with gemini-cli generation the joint sweep+is clean in round 0 for almost every cell, and the judge's remaining *critical*+articulation defects are (a) a joint that moves the wrong way — which+``motion_direction`` already measures, and whose fix is a sign — and (b) a link buried+inside another so it can neither be seen nor move. Most cells stop on the dollar cap+after one or two rounds, so a fix that costs a round is a fix that mostly never happens.++* :func:`repair_motion_directions` flips the URDF axis of every joint the motion gate+ found reversed, re-measures, keeps the flip when the re-measurement passes and reverts+ it otherwise. It edits ``src/robot.urdf`` (the agent's file, so later rounds keep it)+ and ``artifacts/robot.urdf`` (what the sweep and the pose sheet read).+* :func:`buried_links` reports a link whose surface lies entirely inside another link's+ watertight mesh at rest.++``CV3D_ART_REPAIRS`` (off unless set; registered in ``plan_features.LIVE_SWITCHES``,+generation-side so an A/B may ``--pin-plan``) turns both on.+"""++from __future__ import annotations++import logging+import re+from pathlib import Path+from typing import Any++import numpy as np+import trimesh++from codeverse.config import _call_time_flag+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity+from codeverse.conventions import to_snake++log = logging.getLogger(__name__)++ART_REPAIRS_ENV = "CV3D_ART_REPAIRS"+#: share of a link's sampled surface that must lie inside ONE other link to call it buried+BURIED_FRACTION = 0.98+BURIED_SAMPLES = 200+++def repairs_enabled() -> bool:+ return _call_time_flag(ART_REPAIRS_ENV, False)+++# ----------------------------------------------------------------------------- axis flip+_JOINT_RE = re.compile(r'(<joint\b[^>]*\bname\s*=\s*"(?P<name>[^"]+)"[^>]*>)(?P<body>.*?)(</joint>)', re.DOTALL)+_AXIS_RE = re.compile(r'<axis\b[^>]*\bxyz\s*=\s*"(?P<xyz>[^"]+)"[^>]*/?>')+++def _negate(xyz: str) -> str:+ vals = [float(v) for v in xyz.replace(",", " ").split()]+ out = []+ for v in vals:+ v = -v+ out.append(f"{int(v)}" if float(v).is_integer() else f"{v:g}")+ return " ".join(out)+++def flip_joint_axis(urdf_text: str, joint: str) -> tuple[str, str | None]:+ """``(new_text, new_xyz)`` with ``joint``'s ``<axis>`` negated (URDF's default axis+ ``1 0 0`` is written out negated when the element is missing); ``(text, None)`` when+ the joint is not in the file. Only that joint's block changes."""+ want = to_snake(joint)+ new_xyz: str | None = None++ def _sub(m: re.Match[str]) -> str:+ nonlocal new_xyz+ if to_snake(m.group("name")) != want or new_xyz is not None:+ return m.group(0)+ body = m.group("body")+ am = _AXIS_RE.search(body)+ if am:+ new_xyz = _negate(am.group("xyz"))+ body = body[:am.start("xyz")] + new_xyz + body[am.end("xyz"):]+ else:+ new_xyz = "-1 0 0"+ body = body.rstrip() + f'\n <axis xyz="{new_xyz}"/>\n '+ return m.group(1) + body + m.group(4)++ text = _JOINT_RE.sub(_sub, urdf_text)+ return text, new_xyz+++def _urdf_files(ws: Any) -> list[Path]:+ return [p for p in (ws.artifacts / "robot.urdf", ws.src / "robot.urdf") if p.is_file()]+++def repair_motion_directions(ws: Any, plan: Any, report: GateReport, *, recheck, events=None) -> GateReport:+ """Flip the axis of every joint ``report`` marks reversed, re-measure with ``recheck``+ (``(ws, plan) -> GateReport | None``), keep what now passes and revert the rest.+ Returns the re-measured report with one WARN line per kept flip (the agent must not+ undo it) and the original ERROR for anything reverted."""+ wrong = [f for f in report.errors if f.target]+ files = _urdf_files(ws)+ if not wrong or not files:+ return report+ originals = {p: p.read_text() for p in files}+ flipped: dict[str, str] = {}+ for f in wrong:+ for p in files:+ text, xyz = flip_joint_axis(p.read_text(), f.target)+ if xyz is not None:+ p.write_text(text)+ flipped[f.target] = xyz+ if not flipped:+ return report+ after = recheck(ws, plan)+ ok_now = {f.target for f in (after.findings if after else []) if f.severity != Severity.ERROR}+ still_wrong = {f.target for f in (after.errors if after else [])}+ kept = {j: xyz for j, xyz in flipped.items() if j in ok_now and j not in still_wrong}+ reverted = {j for j in flipped if j not in kept}+ if reverted:+ # put the reverted joints back by flipping them again (their other edits stand)+ for p in files:+ text = p.read_text()+ for j in reverted:+ text, _ = flip_joint_axis(text, j)+ p.write_text(text)+ if not kept:+ for p, t in originals.items():+ p.write_text(t)+ after = recheck(ws, plan) or report+ if events is not None:+ events.emit("repair.motion_flip", kept=kept, reverted=sorted(reverted))+ findings = list((after.findings if after else []) or [])+ for j, xyz in kept.items():+ findings.append(GateFinding(+ gate=report.gate, severity=Severity.WARN, target=j,+ message=f"harness repair: the axis of joint '{j}' in robot.urdf was flipped to ({xyz}) so its motion "+ f"matches the plan — keep it; do not rewrite this joint's axis or limits",+ data={"kind": "repair", "axis": xyz}))+ passed = not any(f.severity == Severity.ERROR for f in findings)+ return GateReport(gate=report.gate, passed=passed, findings=findings,+ duration_ms=(after.duration_ms if after else report.duration_ms))+++# ----------------------------------------------------------------------------- buried links+def _inside_fraction(body: Any, points_world: np.ndarray) -> float:+ """Share of ``points_world`` inside any of ``body``'s islands (LinkBody keeps geometry in+ the link frame; these bodies were built from world meshes, so T is the identity)."""+ from codeverse.spatial.joints_collide import inside_island++ local = trimesh.transform_points(points_world, body.T_inv)+ mask = np.zeros(len(local), dtype=bool)+ for isl in body.islands:+ mask |= np.asarray(inside_island(isl, local), dtype=bool)+ return float(mask.mean()) if len(mask) else 0.0+++def buried_links(robot: Any, *, samples: int = BURIED_SAMPLES, fraction: float = BURIED_FRACTION) -> list[GateFinding]:+ """Links whose surface lies (almost) entirely inside another link at rest. Uses the+ sweep's own :class:`LinkBody` containment (island-based, works on the open meshes agents+ export) so this check and the collision sweep never disagree about what "inside" means."""+ from codeverse.spatial.joints_collide import LinkBody+ from codeverse.spatial.joints_model import link_world_meshes++ meshes = link_world_meshes(robot, {})+ bodies = {n: LinkBody(n, m) for n, m in meshes.items() if not m.is_empty and m.area > 0}+ out: list[GateFinding] = []+ for name, body in bodies.items():+ pts, _ = trimesh.sample.sample_surface(meshes[name], samples, seed=0)+ lo, hi = meshes[name].bounds+ for other, ob in bodies.items():+ if other == name:+ continue+ olo, ohi = meshes[other].bounds+ if not (np.all(olo <= lo + 1e-6) and np.all(hi <= ohi + 1e-6)):+ continue # not even inside its box+ try:+ frac = _inside_fraction(ob, pts)+ except Exception: # noqa: BLE001 — a degenerate mesh; skip, never fail the gate+ continue+ if frac >= fraction:+ out.append(GateFinding(+ gate="articulation", severity=Severity.ERROR, target=name,+ message=f"link '{name}' lies entirely inside '{other}' at rest ({frac * 100:.0f}% of its surface): "+ f"it can neither be seen nor move",+ fix_hint=f"move '{name}' outside '{other}' (or cut a pocket in '{other}' where it sits) so the part "+ f"is visible in the rest pose; if it is really internal, merge it into '{other}'",+ data={"kind": "buried", "inside": other, "fraction": round(frac, 3)}))+ break+ return out+++__all__ = ["ART_REPAIRS_ENV", "BURIED_FRACTION", "buried_links", "flip_joint_axis", "repair_motion_directions",+ "repairs_enabled"]diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.pyindex ba1067c0..dafdabf9 100644--- a/harness/codeverse/tracks/plan_features.py+++ b/harness/codeverse/tracks/plan_features.py@@ -33,7 +33,7 @@ GENERATION_SIDE: frozenset[str] = frozenset({CONTACTS})#: pin costs one noisy A/B, pinning wrongly costs a confident wrong answer#: (docs/EVAL.md §8.1 measured it — the A/A's worst pair differed 1 part vs 10).GENERATION_SIDE_ENV: frozenset[str] = frozenset({"CV3D_SKILLS", "CV3D_SKILLS_MAX", "CV3D_SKILLS_UNVERIFIED",- "CV3D_SKILLS_ONLY",+ "CV3D_SKILLS_ONLY", "CV3D_ART_REPAIRS","CV3D_DETAIL_ROUNDS", "CV3D_REFERENCE_DIFF","CV3D_FEWER_TURNS", "CV3D_SEED_RECIPES"})@@ -78,6 +78,9 @@ LIVE_SWITCHES: dict[str, str] = {# prompt inlines its files, the baseline prompt asks for every file in turn 1. One# switch, read at call time by config.fewer_turns_enabled; acts after planning."CV3D_FEWER_TURNS": "codeverse/config.py",+ # deterministic articulated repairs (axis flip on a reversed joint, buried-link check);+ # act after planning — an A/B over it may --pin-plan+ "CV3D_ART_REPAIRS": "codeverse/tracks/articulated_repairs.py","CV3D_SEED_RECIPES": "codeverse/config.py",# model-transport switches (2026-08-28, the hung-read waves): streaming with# inter-chunk stall detection, and the IPv4-only transport. Read at call timediff --git a/harness/tests/threejs_render/test_render_retry.py b/harness/tests/threejs_render/test_render_retry.pynew file mode 100644index 00000000..62b3eb8a--- /dev/null+++ b/harness/tests/threejs_render/test_render_retry.py@@ -0,0 +1,54 @@+"""A transient render failure is retried once with twice the time; a real one is not."""++from __future__ import annotations++from pathlib import Path++import pytest++import codeverse.spatial.render as R+from codeverse.spatial.render import RenderError, render_glb++[email protected](autouse=True)+def _isolated_cache(tmp_path, monkeypatch):+ from codeverse.config import get_settings++ monkeypatch.setenv("CV3D_CACHE_DIR", str(tmp_path / "cache"))+ get_settings.cache_clear()+ monkeypatch.setattr(R, "RETRY_PAUSE_S", 0.0)+ yield+ get_settings.cache_clear()+++def _glb(tmp_path: Path) -> Path:+ p = tmp_path / "x.glb"+ p.write_bytes(b"glTF")+ return p+++def test_transient_failure_is_retried_with_double_timeout(tmp_path, monkeypatch):+ calls: list[float] = []++ def fake(glb, out_dir, params, *, gpu, timeout_s):+ calls.append(timeout_s)+ if len(calls) == 1:+ raise RenderError("render_glb failed: node script render_glb.mjs exited 1: Waiting failed")+ return {"views": [], "renderer": "fake", "duration_ms": 1}++ monkeypatch.setattr(R, "_run_render", fake)+ rs = render_glb(_glb(tmp_path), tmp_path / "out", use_cache=False, timeout_s=100)+ assert rs.renderer == "fake" and calls == [100, 200]+++def test_real_failure_is_not_retried(tmp_path, monkeypatch):+ calls: list[float] = []++ def fake(glb, out_dir, params, *, gpu, timeout_s):+ calls.append(timeout_s)+ raise RenderError("render_glb failed: Cannot find module 'puppeteer'")++ monkeypatch.setattr(R, "_run_render", fake)+ with pytest.raises(RenderError):+ render_glb(_glb(tmp_path), tmp_path / "out", use_cache=False, timeout_s=100)+ assert calls == [100]diff --git a/harness/tests/urdf_joints/test_repairs.py b/harness/tests/urdf_joints/test_repairs.pynew file mode 100644index 00000000..180a0b18--- /dev/null+++ b/harness/tests/urdf_joints/test_repairs.py@@ -0,0 +1,139 @@+"""Deterministic articulated repairs (tracks/articulated_repairs.py)."""++from __future__ import annotations++from pathlib import Path++from codeverse.contracts.artifacts import Severity+from codeverse.spatial.joints import load_urdf+from codeverse.tracks.articulated_repairs import buried_links, flip_joint_axis+from tests.urdf_joints.conftest import box_glb++URDF = """<?xml version="1.0"?>+<robot name="t">+ <link name="body"><visual><geometry><mesh filename="meshes/body.glb"/></geometry></visual></link>+ <link name="door"><visual><geometry><mesh filename="meshes/door.glb"/></geometry></visual></link>+ <link name="knob"><visual><geometry><mesh filename="meshes/knob.glb"/></geometry></visual></link>+ <joint name="hinge" type="revolute">+ <parent link="body"/>+ <child link="door"/>+ <origin xyz="0 0 0" rpy="0 0 0"/>+ <axis xyz="0 0 1"/>+ <limit lower="0" upper="1.57" effort="1" velocity="1"/>+ </joint>+ <joint name="knob_fixed" type="fixed">+ <parent link="door"/>+ <child link="knob"/>+ <origin xyz="0 0 0" rpy="0 0 0"/>+ </joint>+ <joint name="no_axis" type="prismatic">+ <parent link="body"/>+ <child link="knob"/>+ <limit lower="0" upper="0.1" effort="1" velocity="1"/>+ </joint>+</robot>+"""+++def test_flip_negates_only_the_named_joint():+ text, xyz = flip_joint_axis(URDF, "Hinge") # any casing+ assert xyz == "0 0 -1" and '<axis xyz="0 0 -1"/>' in text+ assert text.count("<axis") == URDF.count("<axis") # nothing added elsewhere+ assert text.replace('<axis xyz="0 0 -1"/>', '<axis xyz="0 0 1"/>') == URDF # everything else byte-identical+ again, xyz2 = flip_joint_axis(text, "hinge")+ assert xyz2 == "0 0 1" and again == URDF # an involution+++def test_flip_writes_the_negated_default_axis_when_missing_and_ignores_unknown_joints():+ text, xyz = flip_joint_axis(URDF, "no_axis")+ assert xyz == "-1 0 0" and '<axis xyz="-1 0 0"/>' in text+ same, none = flip_joint_axis(URDF, "not_there")+ assert none is None and same == URDF+ t2, x2 = flip_joint_axis('<joint name="j" type="revolute"><axis xyz="0.5 -0.25 0"/></joint>', "j")+ assert x2 == "-0.5 0.25 0"+++def _two_box_robot(root: Path, *, knob_center) -> Path:+ meshes = root / "meshes"+ meshes.mkdir(parents=True, exist_ok=True)+ box_glb(meshes / "body.glb", (0, 0, 0.5), (0.6, 0.6, 1.0))+ box_glb(meshes / "door.glb", (0.31, 0, 0.5), (0.02, 0.6, 1.0))+ box_glb(meshes / "knob.glb", knob_center, (0.04, 0.04, 0.04))+ urdf = root / "robot.urdf"+ urdf.write_text(URDF.replace(''' <joint name="no_axis" type="prismatic">+ <parent link="body"/>+ <child link="knob"/>+ <limit lower="0" upper="0.1" effort="1" velocity="1"/>+ </joint>+''', ""))+ return urdf+++def test_buried_link_is_reported_and_a_visible_one_is_not(tmp_path):+ r = load_urdf(_two_box_robot(tmp_path / "a", knob_center=(0, 0, 0.5)), tmp_path / "a" / "meshes")+ out = buried_links(r)+ assert [f.target for f in out] == ["knob"] and out[0].severity == Severity.ERROR+ assert out[0].data["inside"] == "body" and out[0].data["fraction"] >= 0.98 and out[0].data["kind"] == "buried"+ r = load_urdf(_two_box_robot(tmp_path / "b", knob_center=(0.35, 0, 0.5)), tmp_path / "b" / "meshes")+ assert buried_links(r) == []+++# ------------------------------------------------------------------ motion-direction repair+class _Events:+ def __init__(self):+ self.items = []++ def emit(self, event, **kw):+ self.items.append((event, kw))+++def _ws(tmp_path):+ from types import SimpleNamespace++ from tests.urdf_joints.conftest import write_mesh_robot++ art = tmp_path / "artifacts"+ src = tmp_path / "src"+ write_mesh_robot(art)+ src.mkdir()+ (src / "robot.urdf").write_text((art / "robot.urdf").read_text())+ return SimpleNamespace(artifacts=art, src=src)+++def test_reversed_hinge_is_flipped_in_both_urdf_copies_and_passes(tmp_path, cabinet_plan):+ from codeverse.tracks.articulated_object import MOTION_GATE, default_motion_checks+ from codeverse.tracks.articulated_repairs import repair_motion_directions++ ws = _ws(tmp_path)+ for p in (ws.artifacts / "robot.urdf", ws.src / "robot.urdf"): # break it: the door now swings into the body+ p.write_text(flip_joint_axis(p.read_text(), "hinge")[0])+ before = default_motion_checks(ws, cabinet_plan)+ assert before is not None and not before.passed and [f.target for f in before.errors] == ["hinge"]+ ev = _Events()+ after = repair_motion_directions(ws, cabinet_plan, before, recheck=default_motion_checks, events=ev)+ assert after.gate == MOTION_GATE and after.passed+ repair = [f for f in after.findings if f.data.get("kind") == "repair"]+ assert len(repair) == 1 and repair[0].severity == Severity.WARN and "keep it" in repair[0].message+ assert '<axis xyz="0 0 -1"/>' in (ws.src / "robot.urdf").read_text()+ assert '<axis xyz="0 0 -1"/>' in (ws.artifacts / "robot.urdf").read_text()+ assert ev.items == [("repair.motion_flip", {"kept": {"hinge": "0 0 -1"}, "reverted": []})]+++def test_a_flip_that_does_not_help_is_reverted(tmp_path, cabinet_plan):+ """The plan says 'front' but the hinge axis is z: flipping changes swing direction, not+ the front/back sense of a door that swings sideways — the flip must not stick."""+ from codeverse.contracts.artifacts import GateFinding, GateReport+ from codeverse.tracks.articulated_object import MOTION_GATE+ from codeverse.tracks.articulated_repairs import repair_motion_directions++ ws = _ws(tmp_path)+ original = (ws.src / "robot.urdf").read_text()+ fake_report = GateReport(gate=MOTION_GATE, passed=False, findings=[GateFinding(+ gate=MOTION_GATE, severity=Severity.ERROR, target="hinge", message="wrong")])++ def still_wrong(ws_, plan_):+ return fake_report++ after = repair_motion_directions(ws, cabinet_plan, fake_report, recheck=still_wrong)+ assert not after.passed and (ws.src / "robot.urdf").read_text() == original+ assert (ws.artifacts / "robot.urdf").read_text() == original