Official Codebase of 3DCodeVerse
Python
tests: spatial_tools, scene_gates, graphics, third pass — internal numbers go, browser boots fold (178 → 155, −330 lines)
gaoypeng5e5de7076dae
diff --git a/harness/tests/scene_gates/test_frame_metrics.py b/harness/tests/scene_gates/test_frame_metrics.pyindex 874aa59c..6932c525 100644--- a/harness/tests/scene_gates/test_frame_metrics.py+++ b/harness/tests/scene_gates/test_frame_metrics.py@@ -26,27 +26,6 @@ def _kinds(report):return [(f.data["kind"], f.severity, f.target) for f in report.findings]-def test_dark_frame_is_error_on_authored_with_concrete_hint_and_warns_on_orbit():- rep = frame_findings(_metrics(_chk("Establishing", mean_lum=0.07, dark_frac=0.41)))- assert not rep.passed- f = rep.findings[0]- assert f.data["kind"] == "dark_frame" and f.severity == Severity.ERROR and f.target == "Establishing"- assert "0.07" in f.message and "41%" in f.message- assert "sunRig(" in f.fix_hint and "fill" in f.fix_hint and "NOT black" in f.fix_hint # the rig env.js builds, not a second sun- assert f.data["view"] == "Establishing" and f.data["mean_lum"] == 0.07- orbit = frame_findings(_metrics(_chk("eye_front", "orbit", mean_lum=0.04, dark_frac=0.77)))- assert orbit.passed and _kinds(orbit) == [("dark_frame", Severity.WARN, "eye_front")]---def test_blown_and_flat_frames():- rep = frame_findings(_metrics(_chk("Cam", blown_frac=0.3), _chk("Flat", modal_frac=0.95), _chk("Soft", modal_frac=0.88)))- kinds = {(k, s) for k, s, _ in _kinds(rep)}- assert ("blown_frame", Severity.ERROR) in kinds- assert ("flat_frame", Severity.ERROR) in kinds # > 0.92 on an authored camera- assert ("flat_frame", Severity.WARN) in kinds # 0.85-0.92- assert not rep.passed--def test_camera_in_geometry_and_near_hit():rep = frame_findings(_metrics(_chk("Buried", camera_in_geometry=True, inside_mesh_bbox=["Tower"], nearest_hit_m=0.1),_chk("Close", nearest_hit_m=0.3)))@@ -127,7 +106,11 @@ def test_scene_rubric_caps_fire_on_frame_kinds():fired = {c.rule: c.cap for c in res.caps_applied}assert fired == {"dark_frame": 0.55, "content_small": 0.6}assert res.overall == 0.55- rep2 = frame_findings(_metrics(_chk("Cam", blown_frac=0.5), _chk("Flat", modal_frac=0.99)))+ rep2 = frame_findings(_metrics(_chk("Cam", blown_frac=0.3), _chk("Flat", modal_frac=0.95), _chk("Soft", modal_frac=0.88)))+ kinds = {(k, s) for k, s, _ in _kinds(rep2)}+ assert ("blown_frame", Severity.ERROR) in kinds and not rep2.passed+ assert ("flat_frame", Severity.ERROR) in kinds # > 0.92 on an authored camera+ assert ("flat_frame", Severity.WARN) in kinds # 0.85-0.92fired2 = {c.rule for c in apply_caps(rubric, 0.9, [rep2], {}, []).caps_applied}assert {"blown_frame", "flat_frame"} <= fired2# orbit-only warnings never capdiff --git a/harness/tests/scene_gates/test_live_frames.py b/harness/tests/scene_gates/test_live_frames.pyindex 172d89d4..a079fae3 100644--- a/harness/tests/scene_gates/test_live_frames.py+++ b/harness/tests/scene_gates/test_live_frames.py@@ -12,6 +12,7 @@ from pathlib import Pathimport pytestfrom PIL import Image+from codeverse3d.contracts.plan import BBoxfrom codeverse3d.conventions import SCENE_VIEWSfrom codeverse3d.proc import read_json_or_nonefrom codeverse3d.spatial.frame_metrics import frame_gate_from_renders@@ -43,8 +44,11 @@ def _darken(ws: Workspace) -> None:def test_example_scene_passes_frame_gate_and_judge_subset(starter_ws: Workspace):+ """Also: plan bounds guard the orbit framing — bounds that contain everything (this run) change+ nothing; a zone that sprawls far past tight bounds is dropped in favour of the zones inside them."""out = starter_ws.renders_dir(0)- rs = render_scene(starter_ws, out, times=(0.0, 1.5), width=640, height=360, fps_seconds=0.3)+ rs = render_scene(starter_ws, out, times=(0.0, 1.5), width=640, height=360, fps_seconds=0.3,+ bounds=BBox(center=(0, 3, 0), extents=(90.0, 10, 90.0)))assert rs.console_errors == []names = {v.name for v in rs.views}assert {"overview", "pond_low", "windmill"} <= names@@ -91,10 +95,18 @@ def test_example_scene_passes_frame_gate_and_judge_subset(starter_ws: Workspace)tile_h = Image.open(rs.views[0].path).size[1]assert sheet.size[1] < 5 * tile_h # 8 tiles in 4 columns → 2 rows, not 5+ assert m["framing_bbox"]["size"][0] == pytest.approx(84.4, abs=0.5) # the meadow (≈ 84 m) fits → framed whole+ y_wide = next(v for v in rs.views if v.name == SCENE_VIEWS[0].name).camera_position[1]+ tight_out = starter_ws.renders_dir(1) # meadow sprawls past 33 m → the pondside zone+ tight = render_scene(starter_ws, tight_out, times=(0.0,), orbit_views=SCENE_VIEWS[:1], width=320, height=180,+ fps_seconds=0, bounds=BBox(center=(0, 3, 0), extents=(30.0, 10, 30.0)), sheet=False)+ assert 10 < read_json_or_none(tight_out / "metrics.json")["framing_bbox"]["size"][0] < 17.5+ assert next(v for v in tight.views if v.name == SCENE_VIEWS[0].name).camera_position[1] < y_wide / 2+def test_dark_variant_raises_dark_frame_errors(starter_ws: Workspace):_darken(starter_ws)- out = starter_ws.renders_dir(1)+ out = starter_ws.renders_dir(2)rs = render_scene(starter_ws, out, times=(0.0,), orbit=False, width=480, height=270, fps_seconds=0)assert rs.views, rs.console_errorsgate = frame_gate_from_renders(out)@@ -104,21 +116,3 @@ def test_dark_variant_raises_dark_frame_errors(starter_ws: Workspace):assert dark[0].target == "overview" and "sunRig(" in dark[0].fix_hint and "NOT black" in dark[0].fix_hintassert dark[0].data["mean_lum"] < 0.12 or dark[0].data["dark_frac"] > 0.35--def test_plan_bounds_guard_orbit_framing(starter_ws: Workspace, tmp_path: Path):- """Plan bounds guard the framing: a zone that sprawls far past the bounds is dropped in- favour of the zones inside them; bounds that contain everything change nothing."""- from codeverse3d.contracts.plan import BBox-- def _run(i: int, extents: float) -> tuple[dict, float]:- out = starter_ws.renders_dir(i)- rs = render_scene(starter_ws, out, times=(0.0,), orbit_views=SCENE_VIEWS[:1], width=320, height=180, fps_seconds=0,- bounds=BBox(center=(0, 3, 0), extents=(extents, 10, extents)), sheet=False)- ov = next(v for v in rs.views if v.name == SCENE_VIEWS[0].name)- return read_json_or_none(out / "metrics.json")["framing_bbox"], ov.camera_position[1]-- wide, y_wide = _run(2, 90.0) # meadow (≈ 84 m) fits → framed as a whole- assert wide["size"][0] == pytest.approx(84.4, abs=0.5)- tight, y_tight = _run(3, 30.0) # meadow sprawls past 33 m → the pondside zone (16.7 m) is framed- assert 10 < tight["size"][0] < 17.5- assert y_tight < y_wide / 2diff --git a/harness/tests/scene_gates/test_live_hero_in_frame.py b/harness/tests/scene_gates/test_live_hero_in_frame.pyindex 20744304..4264ecfa 100644--- a/harness/tests/scene_gates/test_live_hero_in_frame.py+++ b/harness/tests/scene_gates/test_live_hero_in_frame.py@@ -61,15 +61,21 @@ def _with_hero(ws: Workspace, *, hidden: bool, roofed: bool = False, away_camerascene.write_text(text)-def test_a_hero_behind_a_wall_in_every_authored_frame_is_an_error(starter_ws: Workspace):- _with_hero(starter_ws, hidden=True)+def test_a_hero_behind_a_wall_in_every_authored_frame_is_an_error_and_the_rig_lifts_the_room_lid(starter_ws: Workspace):+ """A hero in a room shell, behind a wall from the overview: in the scene, in no authored frame → an ERROR.+ The overview rig hides the harness-injected shell's ceiling when the eye is above it; authored cameras keep it."""+ _with_hero(starter_ws, hidden=True, roofed=True)out = starter_ws.renders_dir(0)rs = render_scene(starter_ws, out, times=(0.0,), width=640, height=360, fps_seconds=0.2)+ assert rs.console_errors == []m = read_json_or_none(out / "metrics.json")row = next(r for r in m["census"]["glb_assets"] if r["url"] == URL)assert row["in_scene"] is True and abs(row["size_m"] - 4.0) < 0.05, row+ assert "RoomShell" in [g["name"] for g in m["census"]["groups"]] # the census counts the shell as builtchk = {c["name"]: c for c in m["camera_checks"]}- assert chk["overview"]["glb_frac"].get(URL, 0.0) < 0.002, chk["overview"]["glb_frac"] # in the scene, behind the wall+ assert chk["overview"]["glb_frac"].get(URL, 0.0) < 0.002, chk["overview"]["glb_frac"] # in the scene, hidden+ # the lid is lifted for the rig: a 4 m cube from 100 m up is a few pixels, but it is there+ assert chk["overview_top"]["glb_frac"].get(URL, 0.0) > 0.0005, chk["overview_top"]["glb_frac"]gate = frame_gate_from_renders(rs)unseen = [f for f in gate.findings if f.data["kind"] == "hero_unseen"]assert len(unseen) == 1 and unseen[0].target == "hero_cube.glb" and not gate.passed, [f.message for f in gate.findings]@@ -80,22 +86,6 @@ def test_a_hero_behind_a_wall_in_every_authored_frame_is_an_error(starter_ws: Woassert math.isfinite(cut[0].data["target_hit_m"])-def test_the_overview_rig_lifts_the_room_shells_lid_but_an_authored_camera_keeps_it(starter_ws: Workspace):- """The rig hides the harness-injected shell's ceiling when the eye is above it; authored cameras keep it."""- _with_hero(starter_ws, hidden=False, roofed=True)- out = starter_ws.renders_dir(0)- rs = render_scene(starter_ws, out, times=(0.0,), width=640, height=360, fps_seconds=0.2)- assert rs.console_errors == []- m = read_json_or_none(out / "metrics.json")- chk = {c["name"]: c for c in m["camera_checks"]}- # the lid is lifted for the rig: a 4 m cube from 100 m up is a few pixels, but it is there- assert chk["overview_top"]["glb_frac"].get(URL, 0.0) > 0.0005, chk["overview_top"]["glb_frac"]- # the authored overview looks at the room from outside and above: the roof stays, the cube is hidden- assert chk["overview"]["glb_frac"].get(URL, 0.0) < 0.002, chk["overview"]["glb_frac"]- names = [g["name"] for g in m["census"]["groups"]]- assert "RoomShell" in names # the census counts the shell as built--def test_a_camera_named_for_the_hero_is_re_aimed_when_the_hero_is_out_of_its_frame(starter_ws: Workspace):"""The host re-aims a hero-named camera at the hero's centre when it is outside the frustum, and logs it."""_with_hero(starter_ws, hidden=False, away_camera=True)diff --git a/harness/tests/scene_gates/test_placement.py b/harness/tests/scene_gates/test_placement.pyindex 5fe76a33..3ed422da 100644--- a/harness/tests/scene_gates/test_placement.py+++ b/harness/tests/scene_gates/test_placement.py@@ -116,28 +116,13 @@ def test_pipeline_gates_are_placement_alone_and_never_raise(tmp_path):assert placement_gate_safe({}, plan=plan) is None-def test_check_placement_reads_the_last_census_and_the_table_text(tmp_path):- from codeverse3d.spatial.registry import ToolContext, get_tool- from codeverse3d.workspace import Workspace-- ws = Workspace(tmp_path / "run").create()- ws.artifacts.mkdir(parents=True, exist_ok=True)- table = _table(_row("Lantern", gap=0.3), _row("Rock", sunk=0.3, into="Terrain", h=1.0))- (ws.artifacts / "census.json").write_text(json.dumps({"totals": {}, "placement": table}))- ws.plan_path.write_text(_contract_plan().model_copy(update={"setting": "a cabin interior"}).model_dump_json())- obs = get_tool("check_placement").call(ToolContext(workspace=ws, language=Language.SCENE_THREEJS.value), {})- assert not obs.ok and "indoor tolerance 2 cm" in obs.text- text = placement_table_text(table)- assert "Yard/Lantern | +0.300 | Ground | 0.000 | - | - | -" in text and "Yard/Rock | +0.000 | Ground | 0.300 | Terrain" in text--def test_check_placement_returns_the_round_gates_verdict(tmp_path):"""The tool's verdict is the round gate's: same census, plan and stage records."""from codeverse3d.spatial.registry import ToolContext, get_toolfrom codeverse3d.workspace import Workspacews = Workspace(tmp_path / "run").create()- census = {"totals": {}, "fog": None, "placement": _table(_row("Lantern", gap=0.3))}+ census = {"totals": {}, "fog": None, "placement": _table(_row("Lantern", gap=0.3), _row("Rock", sunk=0.3, into="Terrain", h=1.0))}(ws.artifacts / "census.json").write_text(json.dumps(census))plan = _contract_plan()ws.plan_path.write_text(plan.model_dump_json())@@ -152,6 +137,12 @@ def test_check_placement_returns_the_round_gates_verdict(tmp_path):kinds = {f.data.get("kind") for f in gate.findings}# Bench was never built: House (its only content) is neither missing it nor emptyassert {"floating", "no_fog"} <= kinds and not {"missing_content", "zone_empty"} & kinds+ # an interior plan: the tighter tolerance is named, and the table text is what the agent reads+ ws.plan_path.write_text(plan.model_copy(update={"setting": "a cabin interior"}).model_dump_json())+ obs = get_tool("check_placement").call(ToolContext(workspace=ws, language=Language.SCENE_THREEJS.value), {})+ assert not obs.ok and "indoor tolerance 2 cm" in obs.text+ text = placement_table_text(census["placement"])+ assert "Yard/Lantern | +0.300 | Ground | 0.000 | - | - | -" in text and "Yard/Rock | +0.000 | Ground | 0.300 | Terrain" in text# --------------------------------------------------------------------- plan-aware contract checksdiff --git a/harness/tests/scene_gates/test_scene_textures_stage.py b/harness/tests/scene_gates/test_scene_textures_stage.pyindex 14df8445..54ef1786 100644--- a/harness/tests/scene_gates/test_scene_textures_stage.py+++ b/harness/tests/scene_gates/test_scene_textures_stage.py@@ -27,30 +27,6 @@ def _render(name: str, **extra):return render(f"tracks/{name}", **base)-GROUND_MANIFEST = {- "raked_zen_gravel": {"file": "raked_zen_gravel.png", "family": "stone", "role": "ground",- "tile_size_m": 1.0, "roughness": 0.95},- "dark_slate_flagstone": {"file": "dark_slate_flagstone.png", "family": "stone", "role": "path",- "tile_size_m": 1.5, "roughness": 0.8},- "aged_cedar_planks": {"file": "aged_cedar_planks.png", "family": "wood", "role": "prop",- "tile_size_m": 0.8, "roughness": 0.75},-}---def test_the_pack_says_outright_that_the_ground_is_what_it_is_for():- """A passive offer loses to the cookbook's ground chapter: the pack names its ground maps outright."""- from codeverse3d.texturing.plan import texture_pack_prompt-- text = texture_pack_prompt(GROUND_MANIFEST)- assert "The ground is what this pack is for" in text- # it names the ground/path maps, and only those- assert "`raked_zen_gravel`" in text and "`dark_slate_flagstone`" in text- tail = text.split("The ground is what this pack is for")[1]- assert "`aged_cedar_planks`" not in tail, "a prop texture is not a ground map"- props = texture_pack_prompt({k: v for k, v in GROUND_MANIFEST.items() if v["role"] == "prop"})- assert "aged_cedar_planks.png" in props and "The ground is what this pack is for" not in props--@pytest.mark.parametrize("template", ["scene_env.j2", "scene_zone.j2"])def test_the_pack_has_the_last_word_over_the_recipes(template: str):"""The cookbook's ground chapter is long and specific; whichever comes last wins."""diff --git a/harness/tests/scene_gates/test_software_fps.py b/harness/tests/scene_gates/test_software_fps.pyindex 2d277743..0ff2102f 100644--- a/harness/tests/scene_gates/test_software_fps.py+++ b/harness/tests/scene_gates/test_software_fps.py@@ -2,22 +2,12 @@from __future__ import annotations-import pytest-from codeverse3d.contracts.artifacts import RenderSetGPU = "ANGLE (NVIDIA Corporation, NVIDIA RTX 6000 Ada Generation, Vulkan)"CPU = "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"[email protected]("renderer,software", [- ("Mesa/X.org llvmpipe (LLVM 15.0.7, 256 bits)", True),- ("", False), # unknown: not claimable as software-])-def test_the_renderer_string_decides(renderer: str, software: bool) -> None:- assert RenderSet(renderer=renderer, fps=9.0).software_rendered is software--def test_the_gate_does_not_fire_on_a_cpu_frame_rate() -> None:from types import SimpleNamespacediff --git a/harness/tests/spatial_tools/test_complexity.py b/harness/tests/spatial_tools/test_complexity.pyindex 1f6a5be8..d0f389d2 100644--- a/harness/tests/spatial_tools/test_complexity.py+++ b/harness/tests/spatial_tools/test_complexity.py@@ -1,9 +1,8 @@-"""The objective complexity vector: axes behave, the index orders artifacts, and-the whole thing is deterministic and additive to ``measure_glb``."""+"""The objective complexity vector: the index is the weighted sum of its axes, the bands+are ordered, and degenerate input never raises."""from __future__ import annotations-import mathfrom pathlib import Pathimport pytest@@ -18,47 +17,6 @@ from codeverse3d.spatial.complexity import (from codeverse3d.spatial.measure import part_meshes-def _export(path: Path, parts: dict[str, trimesh.Trimesh]) -> Path:- sc = trimesh.Scene()- for name, mesh in parts.items():- sc.add_geometry(mesh, node_name=name, geom_name=name)- sc.export(str(path))- return path---def primitive_scene(path: Path) -> Path:- """Three unmodified boxes — the box-stack floor of the scale."""- parts = {}- for i, (w, h, y) in enumerate(((0.4, 0.05, 0.42), (0.4, 0.4, 0.2), (0.35, 0.05, 0.02))):- box = trimesh.creation.box(extents=(w, h, 0.4))- box.apply_translation((0, y, 0))- parts[f"Slab_{i}"] = box- return _export(path, parts)---def detailed_scene(path: Path) -> Path:- """The same three slabs plus repeated hardware, a hollow tube and fine bevel- strips: more parts, more small sharp edges, repeated families, hollowness."""- parts = {}- for i, (w, h, y) in enumerate(((0.4, 0.05, 0.42), (0.4, 0.4, 0.2), (0.35, 0.05, 0.02))):- box = trimesh.creation.box(extents=(w, h, 0.4))- box.apply_translation((0, y, 0))- parts[f"Slab_{i}"] = box- for i, (x, z) in enumerate(((-0.15, -0.15), (0.15, -0.15), (-0.15, 0.15), (0.15, 0.15))):- knob = trimesh.creation.icosphere(subdivisions=2, radius=0.012)- knob.apply_translation((x, 0.47, z))- parts[f"Knob_{i}"] = knob- tube = trimesh.creation.annulus(r_min=0.028, r_max=0.035, height=0.3)- tube.apply_transform(trimesh.transformations.rotation_matrix(math.pi / 2, (1, 0, 0)))- tube.apply_translation((0, 0.25, 0.22))- parts["Tube"] = tube- for i in range(6):- strip = trimesh.creation.box(extents=(0.4, 0.004, 0.004))- strip.apply_translation((0, 0.40 + 0.006 * i, -0.2))- parts[f"Bead_{i}"] = strip- return _export(path, parts)--def test_vector_shape_and_weights(stool_glb: Path) -> None:vec = complexity_of_glb(stool_glb)assert set(COMPLEXITY_WEIGHTS) == set(vec.components) == set(vec.axes)@@ -70,16 +28,8 @@ 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)---def test_detail_beats_primitives(tmp_path: Path) -> None:- plain = complexity_of_glb(primitive_scene(tmp_path / "plain.glb"))- rich = complexity_of_glb(detailed_scene(tmp_path / "rich.glb"))- assert rich.index > plain.index + 0.15- assert rich.feature_density > plain.feature_density- assert rich.part_count > plain.part_count- assert rich.symmetry_groups >= 2 > plain.symmetry_groups # knobs and beads repeat- assert rich.hollowness > plain.hollowness+ labels = [band_of(x) for x in (0.0, 0.3, 0.45, 0.6, 0.9, 1.0)]+ assert labels == ["trivial", "simple", "moderate", "complex", "intricate", "intricate"]def test_degenerate_input_never_raises() -> None:@@ -95,8 +45,3 @@ def test_symmetry_groups_count_geometric_families(solid_stool_glb: Path) -> Noneassert vec.symmetry_groups == 1 # the four legs are one family; the seat is aloneassert vec.extra["repeated_parts"] == 4--def test_bands_are_ordered() -> None:- labels = [band_of(x) for x in (0.0, 0.3, 0.45, 0.6, 0.9)]- assert labels == ["trivial", "simple", "moderate", "complex", "intricate"]- assert band_of(1.0) == "intricate"diff --git a/harness/tests/spatial_tools/test_connectivity.py b/harness/tests/spatial_tools/test_connectivity.pyindex 14f6d678..5fb33bfa 100644--- a/harness/tests/spatial_tools/test_connectivity.py+++ b/harness/tests/spatial_tools/test_connectivity.py@@ -216,41 +216,6 @@ def test_thin_rod_through_a_plate_is_measured_and_named_but_severity_stays_on_deassert over[0][2:] == [pytest.approx(5.0, abs=0.5), pytest.approx(d["through_ratio"], abs=0.01)]-def test_a_thin_part_sunk_into_a_thick_one_is_not_through(tmp_path: Path) -> None:- """A 5 mm disc sunk 2.3 mm into a base: the through-ratio is the min over both directions, so a WARN."""- base = trimesh.creation.box(extents=(0.2, 0.05, 0.2))- base.apply_translation((0, 0.025, 0))- disc = _cylinder_y(0.02, 0.005, (0, 0.05 - 0.0023 + 0.0025, 0))-- r = check_connectivity(_scene(tmp_path / "inset.glb", BaseStand=base, FieldIlluminator=disc))-- pen = _penetrations(r)- assert r.passed and len(pen) == 1 and pen[0].severity == Severity.WARN- assert pen[0].data["through_ratio"] < 0.2, pen[0].data- assert "reaches" not in pen[0].message and "where they meet" in pen[0].message---def test_contact_ledger_carries_contacts_overlaps_and_ground_gaps(tmp_path: Path) -> None:- """A 1 mm weld is below the WARN line — no finding — but the INFO ledger lists it for the judge."""- a = trimesh.creation.box(extents=(0.2, 0.2, 0.2))- a.apply_translation((0, 0.1, 0))- b = trimesh.creation.box(extents=(0.1, 0.1, 0.1))- b.apply_translation((0, 0.2 + 0.05 - 0.001, 0))-- r = check_connectivity(_scene(tmp_path / "weld.glb", A=a, B=b))-- assert r.passed and not _penetrations(r)- led = _ledger(r)- assert led.message == "contact ledger: 2 parts, 1 contacts, 1 overlaps"- d = led.data- assert sorted(d["parts"]) == ["A", "B"] and d["contact_gap_mm"] == 2.0- assert len(d["contacts"]) == 1 and set(d["contacts"][0][:2]) == {"A", "B"} and d["contacts"][0][2] == 0.0- assert len(d["overlaps"]) == 1 and set(d["overlaps"][0][:2]) == {"A", "B"}- assert d["overlaps"][0][2] == pytest.approx(1.0, abs=0.1)- assert d["ground_gap_mm"] == {"A": 0.0, "B": pytest.approx(199.0, abs=0.1)}- assert d["planned"] == [] and d["planned_unresolved"] == []--def test_planned_edges_are_measured_regardless_of_the_aabb_prefilter(solid_stool_glb: Path) -> None:"""Leg_0-Seat is a contact; Leg_0-Leg_1 are 260 mm apart, a pair the AABB prefilternever measures — a planned join is measured anyway and reported open, not as an ERRORdiff --git a/harness/tests/spatial_tools/test_contract.py b/harness/tests/spatial_tools/test_contract.pyindex ee4f133b..ebd78861 100644--- a/harness/tests/spatial_tools/test_contract.py+++ b/harness/tests/spatial_tools/test_contract.py@@ -9,7 +9,6 @@ from codeverse3d.contracts.plan import BBox, CameraPlan, PartPlan, ScenePlan, Stfrom codeverse3d.spatial.contract import (check_contract,match_parts,- planned_joins,)from codeverse3d.spatial.measure import measure_glb@@ -25,15 +24,6 @@ def _stool_plan(**overrides) -> StaticPlan:return StaticPlan(**data)-def test_missing_part_is_error(solid_stool_glb: Path) -> None:- plan = _stool_plan()- plan.parts.append(PartPlan(name="Backrest", role="back", description="d", bbox=BBox(center=(0, 0.18, 0.6), extents=(0.4, 0.03, 0.3))))- r = check_contract(measure_glb(solid_stool_glb), plan, language="blender")- assert not r.passed- miss = [f for f in r.errors if f.target == "Backrest"]- assert miss and "missing" in miss[0].message and "40.0×3.0×30.0" in miss[0].fix_hint--def test_bbox_deviation_warn_then_error(solid_stool_glb: Path) -> None:m = measure_glb(solid_stool_glb)plan = _stool_plan()@@ -70,32 +60,6 @@ def test_ground_and_footprint_warnings() -> None:assert "above the ground" in msgs and "footprint centre" in msgs-def test_planned_joins_pair_a_spanning_child_with_every_touching_parent_copy() -> None:- """An X-braced table: every parent copy the brace's box touches is a candidate (ties are not broken by order)."""- plan = StaticPlan(- object_name="Table", summary="s", overall_bbox=BBox(center=(0, 0, 0.375), extents=(1.0, 1.0, 0.75)),- parts=[PartPlan(name="Top", role="top", description="d", bbox=BBox(center=(0, 0, 0.73), extents=(1.0, 1.0, 0.04))),- PartPlan(name="Leg", role="leg", description="d", bbox=BBox(center=(0, 0, 0.355), extents=(0.05, 0.05, 0.71)), attach_to="Top", instances=4),- PartPlan(name="Brace", role="brace", description="d", bbox=BBox(center=(0, 0, 0.2), extents=(0.9, 0.05, 0.03)), attach_to="Leg")])- leg = lambda x, z: PartMeasure(name="", bbox_min=(x - 0.025, 0.0, z - 0.025), bbox_max=(x + 0.025, 0.71, z + 0.025)) # noqa: E731- rows = [PartMeasure(name="Top", bbox_min=(-0.5, 0.71, -0.5), bbox_max=(0.5, 0.75, 0.5))]- for i, (x, z) in enumerate([(0.45, 0.45), (0.45, -0.45), (-0.45, 0.5), (-0.45, -0.45)]):- rows.append(leg(x, z).model_copy(update={"name": f"Leg_{i}"}))- # a diagonal brace from Leg_1 (0.45, -0.45) to Leg_3 (-0.45, -0.45) with a lug rising toward Leg_0: one AABB- # covers the whole span, so it overlaps Leg_0's box (z 0.425..0.475) and stops 3.5 cm short of Leg_2's (z ≥ 0.475)- rows.append(PartMeasure(name="Brace", bbox_min=(-0.46, 0.185, -0.46), bbox_max=(0.46, 0.215, 0.44)))- m = Measurement(bbox_min=(-0.5, 0, -0.5), bbox_max=(0.5, 0.75, 0.5), extents=(1, 0.75, 1), center=(0, 0.375, 0),- tri_count=12 * len(rows), n_meshes=len(rows), n_islands=len(rows), parts=rows)-- edges = planned_joins(plan, m)- groups = {child: set(parents) for child, parents in edges}- brace = groups["Brace"] # one group: the copies the brace's box touches, measured by the gate, not guessed-- assert {"Leg_1", "Leg_3"} <= brace and "Leg_0" in brace # the two it spans plus the grazed copy — measured, not guessed- assert "Leg_2" not in brace # clear of the AABB: never a candidate- assert [e for e in edges if e[0].startswith("Leg")] == [(f"Leg_{i}", ("Top",)) for i in range(4)]--def test_an_exact_name_wins_over_another_part_instance_pattern() -> None:"""An exact name wins over another part's instance pattern ('Slat1' is not an instance of Slat)."""plan = [PartPlan(name=n, role="r", description="d", bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)))@@ -171,13 +135,10 @@ def _orientation(findings: list[GateFinding]) -> list[GateFinding]:return [f for f in findings if f.data.get("kind") == "orientation"]-def test_a_standing_box_has_no_orientation_finding() -> None:- # Blender plan 40×20 cm footprint, 120 cm tall → GLB (0.4, 1.2, 0.2)+def test_a_box_rotated_90_about_x_is_lying_down() -> None:+ # Blender plan 40×20 cm footprint, 120 cm tall → GLB (0.4, 1.2, 0.2): standing, no orientation findingr = check_contract(_measurement_glb((0.4, 1.2, 0.2)), _one_part_plan((0.4, 0.2, 1.2), up=2), language="blender")assert r.passed and not _orientation(r.findings)---def test_a_box_rotated_90_about_x_is_lying_down() -> None:r = check_contract(_measurement_glb((0.4, 0.2, 1.2)), _one_part_plan((0.4, 0.2, 1.2), up=2), language="blender")o = _orientation(r.findings)assert len(o) == 1 and o[0].severity == Severity.ERROR and not r.passeddiff --git a/harness/tests/spatial_tools/test_mcp_server.py b/harness/tests/spatial_tools/test_mcp_server.pyindex aa7fedf1..52b27c5f 100644--- a/harness/tests/spatial_tools/test_mcp_server.py+++ b/harness/tests/spatial_tools/test_mcp_server.py@@ -61,9 +61,7 @@ def test_the_byte_bound_keeps_the_sheet_drops_the_rest_and_says_so(tmp_path: Patfrom codeverse3d.spatial.mcp_server import MAX_IMAGE_BYTES, encode_imagedef noise(name: str, side: int) -> str:- rnd = __import__("random").Random(len(name))- img = Image.new("RGB", (side, side))- img.putdata([(rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)) for _ in range(side * side)])+ img = Image.frombytes("RGB", (side, side), __import__("random").Random(len(name)).randbytes(side * side * 3))p = tmp_path / nameimg.save(p)return str(p)diff --git a/harness/tests/spatial_tools/test_render_common.py b/harness/tests/spatial_tools/test_render_common.pyindex c09d395f..e3f26455 100644--- a/harness/tests/spatial_tools/test_render_common.py+++ b/harness/tests/spatial_tools/test_render_common.py@@ -1,4 +1,4 @@-"""Render caching: one cache authority, keyed by content and GPU mode, safe under concurrent writers."""+"""Render caching: one cache authority, keyed by content, safe under concurrent writers."""from __future__ import annotations@@ -78,33 +78,6 @@ def test_store_in_cache_survives_a_concurrent_identical_writer(tmp_path: Path, massert not list(cache_dir.parent.glob("*.tmp")), "no tmp dirs left behind"-def test_object_render_cache_is_keyed_by_gpu_mode(stool_glb: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """The requested GPU mode is part of the cache key: gpu=off is never served gpu=on's pixels."""- from types import SimpleNamespace-- from codeverse3d.spatial import render as R-- runs: list[tuple[str, Path]] = []-- def fake_run_render(glb, out_dir, params, *, gpu, timeout_s):- runs.append((gpu, Path(out_dir)))- (Path(out_dir) / "view_front.png").write_bytes(b"png-" + gpu.encode())- return {"views": [{"name": "front"}], "renderer": f"webgl-{gpu}"}-- fake_settings = SimpleNamespace(cache_dir=tmp_path / "cache",- render=SimpleNamespace(gpu="auto"),- limits=SimpleNamespace(render_timeout_s=5))- monkeypatch.setattr(R, "get_settings", lambda: fake_settings)- monkeypatch.setattr(R, "_run_render", fake_run_render)-- a = R.render_glb(stool_glb, tmp_path / "a", views=[OBJECT_VIEWS[0]], sheet=False, gpu="on")- b = R.render_glb(stool_glb, tmp_path / "b", views=[OBJECT_VIEWS[0]], sheet=False, gpu="off")- assert len(runs) == 2, "gpu=off must not be served gpu=on's cached pixels"- assert a.renderer == "webgl-on" and b.renderer == "webgl-off"- c = R.render_glb(stool_glb, tmp_path / "c", views=[OBJECT_VIEWS[0]], sheet=False, gpu="on")- assert len(runs) == 2 and c.renderer == "webgl-on", "same mode still hits the cache"--def test_gl_metrics_summary_is_the_one_frame_stats_formatter(tmp_ws: Workspace, monkeypatch: pytest.MonkeyPatch) -> None:from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severityfrom codeverse3d.spatial.frame_stats import FrameStat, SequenceStatsdiff --git a/harness/tests/spatial_tools/test_sections.py b/harness/tests/spatial_tools/test_sections.pyindex d29280e4..a45433e6 100644--- a/harness/tests/spatial_tools/test_sections.py+++ b/harness/tests/spatial_tools/test_sections.py@@ -25,14 +25,6 @@ def test_cross_section_that_cuts_nothing_answers_without_an_image(tmp_path: Pathassert not (tmp_path / "gap.png").exists()-def test_hollow_ratio(tmp_path: Path) -> None:- p = tmp_path / "tube.glb"- trimesh.creation.annulus(r_min=0.04, r_max=0.05, height=0.3).export(str(p))- o = cross_section(p, "z", 0.5, tmp_path / "t.png")- assert o.numbers["n_loops"] == 2- assert o.numbers["hollow_ratio"] == pytest.approx(0.64, abs=0.03)--def test_bad_inputs(stool_glb: Path, tmp_path: Path) -> None:assert not cross_section(stool_glb, "w", 0.5, tmp_path / "x.png").oko = cross_section(stool_glb, "y", 0.5, tmp_path / "x.png", parts=["Nope"])@@ -55,23 +47,6 @@ def _two_boxes(path: Path, *, overlap_x: float = 0.05, dy: float = 0.0) -> Path:return path-def test_judge_slices_hatches_only_gate_error_pairs(tmp_path: Path) -> None:- glb = _two_boxes(tmp_path / "boxes.glb")- m = judge_slices(glb, [("A", "B")], tmp_path / "err")- assert [s.name for s in m.rendered()] == ["front_back", "left_right"]- assert m.error_pairs == [("A", "B")]- for s in m.rendered():- assert [(p.a, p.b) for p in s.hatched_pairs] == [("B", "A")] or \- [(p.a, p.b) for p in s.hatched_pairs] == [("A", "B")]- assert s.plain_pairs == []- assert (tmp_path / "err" / s.png).is_file()-- # the SAME geometry with no gate-ERROR pair: plain darkened blend, no hatch (F1)- plain = judge_slices(glb, [], tmp_path / "plain")- for s in plain.rendered():- assert s.hatched_pairs == [] and len(s.plain_pairs) == 1--def test_judge_slices_ignores_hairline_contact_slivers(tmp_path: Path) -> None:# 1 mm of in-plane overlap (a weld) is under the ~2·erode thickness: not drawn at allglb = _two_boxes(tmp_path / "weld.glb", overlap_x=0.3, dy=0.299) # stacked, 1 mm y-overlapdiff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.pyindex f620b233..bbc72def 100644--- a/harness/tests/spatial_tools/test_tools.py+++ b/harness/tests/spatial_tools/test_tools.py@@ -18,43 +18,9 @@ from codeverse3d.contracts.artifacts import (Severity,)from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan-from codeverse3d.spatial.registry import ToolContext, get_tool, list_tools+from codeverse3d.spatial.registry import ToolContext, get_toolfrom codeverse3d.workspace import Workspace-#: tools every workspace gets (no track/language restriction)-CORE_TOOLS = {"build", "measure", "render_views", "render_sheet", "isolate", "cross_section", "check_connectivity",- "check_contract", "compare_reference"}-#: track- / language-scoped tools (documented; keep in sync when registering a new one)-SCOPED_TOOLS = {- "joint_sweep", # articulated_object- "shader_probe", "scene_probe", "scene_views", "check_placement", # scene_threejs- "gl_probe", "gl_frames", # graphics (glsl_shader / opengl_python)-}-EXPECTED_TOOLS = CORE_TOOLS | SCOPED_TOOLS---def test_registry_has_every_tool() -> None:- registered = {t.name for t in list_tools()}- assert registered == EXPECTED_TOOLS, (- f"registry drifted: unexpected {sorted(registered - EXPECTED_TOOLS)}, "- 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- scene = {t.name for t in list_tools(track="scene", language="scene_threejs")}- assert "shader_probe" in scene- graphics = {t.name for t in list_tools(track="graphics", language="glsl_shader")}- assert {"gl_probe", "gl_frames"} <= graphics and "scene_probe" not in graphics- # V11a: the object-GLB toolset never reaches scene/graphics agents — their builds- # never write artifacts/object.glb, so every one of these was a dead-end refusal- object_glb_tools = {"measure", "check_connectivity", "check_contract", "cross_section", "isolate",- "render_views", "render_sheet", "compare_reference"}- assert not object_glb_tools & scene and not object_glb_tools & graphics- assert "build" in scene and "build" in graphics # build itself stays universal- articulated = {t.name for t in list_tools(track="articulated_object", language="urdf_blender")}- assert object_glb_tools | {"joint_sweep"} <= articulated # articulated keeps the object toolset- for t in list_tools():- assert t.schema()["type"] == "object" and t.description-def test_measure_tool(stool_ctx: ToolContext) -> None:obs = get_tool("measure").call(stool_ctx, {})@@ -114,28 +80,6 @@ def _patch_runtime(monkeypatch: pytest.MonkeyPatch, rt: _FakeRuntime) -> None:monkeypatch.setattr(langs, "get_runtime", lambda language: rt)-def test_build_tool_success(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:- glb = stool_ctx.workspace.artifacts / "object.glb"- _patch_runtime(monkeypatch, _FakeRuntime(glb=glb))- obs = get_tool("build").call(stool_ctx, {})- assert obs.ok and obs.text.startswith("BUILD OK") and "Leg ×4" in obs.text- assert "lint warnings" in obs.text and "uses bpy.ops.render" in obs.text and "build warnings" in obs.text- assert str(stool_ctx.workspace.root) not in obs.text- assert json.loads((stool_ctx.workspace.artifacts / "build.json").read_text())["ok"] is True- assert (stool_ctx.workspace.artifacts / "measurement.json").is_file()---def test_build_tool_failure_is_error_first(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:- _patch_runtime(monkeypatch, _FakeRuntime(build_ok=False))- obs = get_tool("build").call(stool_ctx, {})- assert not obs.ok- first = obs.text.splitlines()[0]- assert first.startswith("BUILD FAILED: NameError: name 'bpyx' is not defined at src/model.py:7")- assert "l59" in obs.text and "l10" not in obs.text # ≤ 30-line stderr tail- assert str(stool_ctx.workspace.root) not in obs.text- assert obs.numbers["error_line"] == 7--def test_a_negative_verdict_is_not_a_tool_failure(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:"""``ok`` is the verdict, ``failed`` is 'the tool could not run' (only that is an MCP error); FAIL leads the text."""import codeverse3d.spatial.tools as ts@@ -161,6 +105,10 @@ def test_a_negative_verdict_is_not_a_tool_failure(stool_ctx: ToolContext, monkey_patch_runtime(monkeypatch, _FakeRuntime(build_ok=False)) # code that will not runobs = get_tool("build").call(stool_ctx, {})assert not obs.ok and not obs.failed and obs.text.startswith("BUILD FAILED")+ # the error leads, at a workspace-relative path, with a ≤ 30-line stderr tail+ assert obs.text.splitlines()[0].startswith("BUILD FAILED: NameError: name 'bpyx' is not defined at src/model.py:7")+ assert "l59" in obs.text and "l10" not in obs.text+ assert str(stool_ctx.workspace.root) not in obs.text and obs.numbers["error_line"] == 7_patch_runtime(monkeypatch, _FakeRuntime(lint_errors=True))obs = get_tool("build").call(stool_ctx, {})assert not obs.ok and not obs.failed and obs.text.startswith("LINT FAILED")@@ -177,7 +125,11 @@ def test_build_that_leaves_no_readable_glb_is_a_failure(stool_ctx: ToolContext,def test_build_lint_fail_refuses_stale_glb(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:"""A lint refusal is the latest build status: the previous GLB is no longer readable as current."""_patch_runtime(monkeypatch, _FakeRuntime(glb=stool_ctx.workspace.artifacts / "object.glb"))- assert get_tool("build").call(stool_ctx, {}).ok+ obs = get_tool("build").call(stool_ctx, {})+ assert obs.ok and obs.text.startswith("BUILD OK") and "Leg ×4" in obs.text+ assert "lint warnings" in obs.text and "uses bpy.ops.render" in obs.text and "build warnings" in obs.text+ assert str(stool_ctx.workspace.root) not in obs.text+ assert (stool_ctx.workspace.artifacts / "measurement.json").is_file()_patch_runtime(monkeypatch, _FakeRuntime(lint_errors=True))obs = get_tool("build").call(stool_ctx, {})assert not obs.ok and obs.text.startswith("LINT FAILED")@@ -341,28 +293,6 @@ def test_build_tool_scene_reports_probe_census(tmp_ws: Workspace, monkeypatch: passert obs.numbers["census"]["fps"] == 58.0-def test_build_tool_graphics_reports_frames(tmp_ws: Workspace, monkeypatch: pytest.MonkeyPatch) -> None:- import codeverse3d.languages._gl_common as gl_build # the one metrics reader (gl_build is a shim over it)- from codeverse3d.spatial.frame_stats import FrameStat, SequenceStats-- ctx = ToolContext(workspace=tmp_ws, language="glsl_shader", track="graphics")- rt = _NoGlbRuntime("glsl_shader", {"renderer": "moderngl"},- {"frames": str(tmp_ws.artifacts / "frames"), "sheet": str(tmp_ws.artifacts / "frames_sheet.png")})- _patch_runtime(monkeypatch, rt)- def _frame(t: float, path: str) -> FrameStat:- return FrameStat(time=t, path=path, mean_lum=0.4, std_lum=0.2, pct_black=0.01, pct_blown=0.01,- colourfulness=0.3, edge_density=0.05)-- stats = SequenceStats(frames=[_frame(0.0, "f0.png"), _frame(1.0, "f1.png")], mean_diff=0.1)- gate = GateReport(gate="gl_frames", passed=True)- monkeypatch.setattr(gl_build, "read_metrics", lambda ws: (stats, gate))- obs = get_tool("build").call(ctx, {})- assert obs.ok, obs.text- assert "no GLB path" not in obs.text- assert "frames=2" in obs.text and "sheet:" in obs.text- assert obs.numbers["n_frames"] == 2 and obs.numbers["gate_errors"] == 0--class _GlRuntime(_NoGlbRuntime):"""Graphics runtime whose build takes the gl tools' kwargs (times / preview / size)."""@@ -377,9 +307,23 @@ def test_gl_tools_lead_with_the_frame_gate_verdict(tmp_ws: Workspace, monkeypatcfrom codeverse3d.spatial.frame_stats import FrameStat, SequenceStatsctx = ToolContext(workspace=tmp_ws, language="glsl_shader", track="graphics")- _patch_runtime(monkeypatch, _GlRuntime("glsl_shader", {"renderer": "moderngl"}))- stats = SequenceStats(frames=[FrameStat(time=0.0, path="f0.png", mean_lum=0.4, std_lum=0.2, pct_black=0.01,- pct_blown=0.01, colourfulness=0.3, edge_density=0.05)], mean_diff=0.0)+ _patch_runtime(monkeypatch, _GlRuntime("glsl_shader", {"renderer": "moderngl"},+ {"frames": str(tmp_ws.artifacts / "frames"),+ "sheet": str(tmp_ws.artifacts / "frames_sheet.png")}))++ def _frame(t: float, path: str) -> FrameStat:+ return FrameStat(time=t, path=path, mean_lum=0.4, std_lum=0.2, pct_black=0.01, pct_blown=0.01,+ colourfulness=0.3, edge_density=0.05)++ # a passing gate: a graphics build (no GLB) reports its frames and sheet+ two = SequenceStats(frames=[_frame(0.0, "f0.png"), _frame(1.0, "f1.png")], mean_diff=0.1)+ monkeypatch.setattr(gl_build, "read_metrics", lambda ws: (two, GateReport(gate="gl_frames", passed=True)))+ obs = get_tool("build").call(ctx, {})+ assert obs.ok, obs.text+ assert "no GLB path" not in obs.text and "frames=2" in obs.text and "sheet:" in obs.text+ assert obs.numbers["n_frames"] == 2 and obs.numbers["gate_errors"] == 0++ stats = SequenceStats(frames=[_frame(0.0, "f0.png")], mean_diff=0.0)bad = GateReport(gate="gl_frames", passed=False, findings=[GateFinding(gate="gl_frames", severity=Severity.ERROR, message="static image", data={"kind": "static"},fix_hint="animate with u_time")])@@ -400,18 +344,3 @@ def _stool_plan_with_missing_backrest() -> StaticPlan:parts=[PartPlan(name="Seat", role="r", description="d", bbox=BBox(center=(0, 0, 0.43), extents=(0.4, 0.4, 0.04))),PartPlan(name="Leg", role="r", description="d", bbox=BBox(center=(0, 0, 0.205), extents=(0.04, 0.04, 0.41)), instances=4),PartPlan(name="Backrest", role="r", description="d", bbox=BBox(center=(0, 0.18, 0.6), extents=(0.4, 0.03, 0.3)))])---def test_connectivity_tool_resolves_instance_names_like_the_track_does(stool_ctx: ToolContext) -> None:- """The tool resolves planned joins (``Leg`` → ``Leg_0..3``) through ``planned_joins``, as the track's gate does."""- ws = stool_ctx.workspace- ws.write_json(ws.plan_path, StaticPlan(- object_name="Stool", summary="s", overall_bbox=BBox(center=(0, 0, 0.225), extents=(0.4, 0.4, 0.45)),- parts=[PartPlan(name="Seat", role="r", description="d", bbox=BBox(center=(0, 0, 0.43), extents=(0.4, 0.4, 0.04))),- PartPlan(name="Leg", role="r", description="d", bbox=BBox(center=(0, 0, 0.205), extents=(0.04, 0.04, 0.41)), attach_to="Seat", instances=4)]))- get_tool("check_connectivity").call(stool_ctx, {})- report = json.loads((ws.gates_dir(0) / "connectivity_tool.json").read_text())- ledger = next(f["data"] for f in report["findings"] if "planned" in (f.get("data") or {}))- assert ledger["planned_unresolved"] == []- assert {(a, b) for a, b, *_ in ledger["planned"]} == {(f"Leg_{i}", "Seat") for i in range(4)}- assert {row[3] for row in ledger["planned"] if row[0] == "Leg_3"} == {"open"} # the 5 mm floating leg