Skip to content

Official Codebase of 3DCodeVerse

Python

spatial: the gate measures overlap where it is, keeps its ledger, and gates orientation

gaoypeng17598102a85f
diff --git a/harness/codeverse/spatial/connectivity.py b/harness/codeverse/spatial/connectivity.py
index eae78827..de117a21 100644
--- a/harness/codeverse/spatial/connectivity.py
+++ b/harness/codeverse/spatial/connectivity.py
@@ -13,11 +13,24 @@ Mechanism
y ≤ gap) — or the largest component when nothing touches the ground.
4. Parts outside the support component are **floating** → ERROR with the
nearest supported part and the exact translation vector that closes the gap.
-5. Overlapping AABB pairs are probed for mutual containment of surface samples;
- a depth above ``PENETRATION_WARN_M`` → WARN, above ``PENETRATION_ERROR_M``
- → ERROR (parts are allowed to overlap by a hair for welding, not to pass
- through each other).
+5. Overlapping AABB pairs are probed for mutual containment of surface samples
+ (:func:`penetration_probe`): the whole surface first, then densely where the
+ overlap is, so the tip of a thin member inside another part is measured with
+ enough points. A pair is reported when the depth is above
+ ``PENETRATION_WARN_M`` and the overlap is either a visible share of the whole
+ part (``PENETRATION_MIN_FRACTION``) or dense where it is
+ (``PENETRATION_MIN_INSIDE`` / ``PENETRATION_MIN_LOCAL_FRACTION``); ERROR
+ above ``PENETRATION_ERROR_M`` when the overlap is also a visible share of the
+ part, else WARN (parts are allowed to overlap by a hair for welding, not to
+ pass through each other; a deep overlap only the dense pass can see is
+ reported in full and left to the judge). The through-ratio — how far
+ the entering member reaches into the part it enters — is measured and named in
+ the message, never a severity (``THROUGH_FAR_SIDE_RATIO``).
6. Tiny disconnected islands inside a single part → WARN (stray geometry).
+7. One INFO *contact ledger*: every contact with its gap, every measured overlap
+ down to the sub-threshold welds, the ground gap per part and the plan's
+ ``attach_to`` edges measured regardless of the AABB prefilter
+ (``planned_edges``). INFO never changes ``passed``; the judge payload reads it.
All thresholds are module constants (meters) and keyword-overridable. Pass the
authoring ``language`` so translation hints are written in the frame the agent
@@ -29,6 +42,7 @@ from __future__ import annotations
import itertools
import time
+from collections.abc import Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -44,15 +58,47 @@ from codeverse.spatial.joints_collide import fcl_collision_object, inside_island
from codeverse.spatial.measure import GlbLoadError, fmt_vec, solid_parts
GATE = "connectivity"
+#: one planned join: (child, parent) or (child, (parent copies the child's box touches, …))
+PlannedEdge = tuple[str, "str | Sequence[str]"]
#: parts smaller than this (max extent) are ignored for floating checks (INFO only)
MIN_PART_SIZE_M = 0.01
#: penetration depth that is reported as WARN / ERROR
PENETRATION_WARN_M = 0.002
PENETRATION_ERROR_M = 0.010
-#: fraction of one part's samples inside the other before we call it penetration
+#: fraction of one part's samples inside the other before we call it penetration ...
PENETRATION_MIN_FRACTION = 0.02
+#: ... or, when the overlap is a small share of a large part, dense where it is: at
+#: least this many samples inside and this share of the samples in the overlap region.
+#: Measured 2026-08-30 on h2h_telescope: the spreader arm tips 4 mm inside three 24 mm
+#: legs were 4–6 of 600 whole-surface samples (0.7–1.0 %), under the fraction floor,
+#: while a third of the arm's surface at the joint was inside the leg.
+PENETRATION_MIN_INSIDE = 4
+PENETRATION_MIN_LOCAL_FRACTION = 0.2
+#: through_ratio = 2 · depth / thickness of the part entered: 1 means the entering
+#: member reaches the far side (the rubric's "rail poking out of the far side of a leg").
+#: It is MEASURED AND REPORTED, never a severity of its own: the corpus re-run
+#: (2026-08-30, 217 runs) showed a 0.9 ERROR line firing on 31 pairs in 9 runs that are
+#: designed joinery — a boom seated 5 mm into a mast (0.96), arch stretchers 8 mm into
+#: 8 mm ribs (0.91–0.97) — because the number saturates at the container's mid-plane and
+#: cannot tell "ends inside" from "out the far side". Severity stays on depth alone
+#: (the contract's own 2 mm / 10 mm lines); the judge, who sees the picture, gets the
+#: ratio as a fact in the message and the ledger.
+THROUGH_FAR_SIDE_RATIO = 0.9
#: surface samples per part for containment / fallback distance tests
N_SAMPLES = 600
+#: when fewer than LOCAL_MIN_SAMPLES of the entering part's whole-surface samples lie in
+#: the overlap region, LOCAL_EXTRA_SAMPLES more are drawn on its faces CLIPPED to the region
+#: (a plate's 300 mm face around an 8 mm rod is 0.05 % in-region; rejection sampling it
+#: never reached the rod's axis). The max depth of a finite sample under-estimates the
+#: true reach by ~ radius/√n, which is why 512 and not 64: at 64, a 24 mm rail through a
+#: 10 mm plate read 0.89, one hair under THROUGH_FAR_SIDE_RATIO
+LOCAL_MIN_SAMPLES = 128
+LOCAL_EXTRA_SAMPLES = 512
+#: the entering part's vertices inside the AABB overlap are tested too: a tip's end cap
+#: is a vertex ring, and vertices find an overlap smaller than 1/N_SAMPLES of the
+#: surface that uniform samples miss (capped so a 200k-vertex part is one ray pass)
+LOCAL_MAX_VERTICES = 1500
+_REGION_HAIR_M = 0.001
#: an island is "tiny" when its largest extent is below this fraction of the part's
TINY_ISLAND_FRACTION = 0.05
_RNG_SEED = 7
@@ -72,17 +118,72 @@ class PairDistance:
return tuple(float(pb - pa) for pa, pb in zip(self.point_a, self.point_b, strict=True)) # type: ignore[return-value]
-class _FclObjects:
- """Lazily-memoized ``fcl.CollisionObject`` per part (None entries when fcl is missing)."""
+@dataclass(frozen=True)
+class Penetration:
+ """The deepest direction of an overlap probe: ``entering``'s surface inside ``container``.
+
+ ``fraction_inside`` is the share of N_SAMPLES whole-surface samples inside the other
+ part, max over both directions — the pre-2026-08-30 number, kept for comparability
+ across the corpus. ``local_fraction`` / ``inside_count`` are measured on the samples
+ that lie in the overlap region only, which is what makes a 10 mm tip on a 400 mm arm
+ visible; ``thickness_m`` is the container's (:func:`part_thickness`).
+
+ ``through_ratio`` is the PAIR's: the smaller of the two directions' 2 · depth /
+ thickness. One direction alone reads a 5 mm disc sunk 2.3 mm into a base as "the base
+ reaches 82 % of the way through the disc" (h2h_microscope FieldIlluminator) — a designed
+ inset. A member that really passes through another scores ≈ 1 both ways: the rod
+ reaches the plate's mid-plane AND the plate's faces cut through the rod's whole
+ cross-section; an inset or socket is high one way and low the other."""
+
+ entering: str
+ container: str
+ depth_m: float = 0.0
+ fraction_inside: float = 0.0
+ local_fraction: float = 0.0
+ inside_count: int = 0
+ thickness_m: float = 0.0
+ through_ratio: float = 0.0
+
+ @property
+ def own_through_ratio(self) -> float:
+ """This direction's 2 · depth / thickness of the container, clipped to [0, 2]: the
+ deepest a surface point can sit inside a member is half its thickness."""
+ if self.thickness_m <= 0.0:
+ return 0.0
+ return float(min(2.0, max(0.0, 2.0 * self.depth_m / self.thickness_m)))
+
+ def as_data(self) -> dict[str, Any]:
+ return {"entering": self.entering, "container": self.container, "depth_m": self.depth_m,
+ "fraction_inside": self.fraction_inside, "local_fraction": self.local_fraction,
+ "inside_count": self.inside_count, "through_ratio": self.through_ratio, "thickness_m": self.thickness_m}
+
+
+class _PartCache:
+ """Per-part collision geometry built once and shared across every pair: the
+ ``fcl.CollisionObject`` (None when fcl is missing), the oriented islands the
+ containment test runs on, and the thickness. Before 2026-08-30 the islands were
+ re-split per pair — on a 20-part model that is ~190 splits of the same 20 meshes."""
def __init__(self, parts: dict[str, trimesh.Trimesh]):
self._parts = parts
- self._objs: dict[str, Any] = {}
+ self._fcl: dict[str, Any] = {}
+ self._islands: dict[str, list[trimesh.Trimesh]] = {}
+ self._thickness: dict[str, float] = {}
- def get(self, name: str) -> Any:
- if name not in self._objs:
- self._objs[name] = fcl_collision_object(self._parts[name])
- return self._objs[name]
+ def fcl(self, name: str) -> Any:
+ if name not in self._fcl:
+ self._fcl[name] = fcl_collision_object(self._parts[name])
+ return self._fcl[name]
+
+ def islands(self, name: str) -> list[trimesh.Trimesh]:
+ if name not in self._islands:
+ self._islands[name] = oriented_islands(self._parts[name])
+ return self._islands[name]
+
+ def thickness(self, name: str) -> float:
+ if name not in self._thickness:
+ self._thickness[name] = part_thickness(self._parts[name])
+ return self._thickness[name]
def _aabb_gap(a: trimesh.Trimesh, b: trimesh.Trimesh) -> float:
@@ -137,8 +238,22 @@ def _sample(mesh: trimesh.Trimesh, n: int, rng: np.random.Generator) -> np.ndarr
return np.asarray(pts, dtype=float)
-def penetration_depth(a: trimesh.Trimesh, b: trimesh.Trimesh, n: int = N_SAMPLES) -> tuple[float, float]:
- """(max depth, fraction of samples inside) of ``a``'s surface inside ``b`` and vice versa.
+def part_thickness(mesh: trimesh.Trimesh) -> float:
+ """Thinnest extent of ``mesh``: the smaller of its AABB and its PCA-aligned box —
+ a tube's diameter or a plate's thickness whichever way it is turned. The AABB
+ alone reads a diagonal 24 mm tripod leg as 311 mm (h2h_telescope TripodLegs_1)."""
+ v = np.asarray(mesh.vertices, dtype=float)
+ ext = float(np.min(mesh.extents))
+ if len(v) < 4:
+ return ext
+ c = v - v.mean(axis=0)
+ _, axes = np.linalg.eigh(c.T @ c)
+ p = c @ axes
+ return float(min(ext, np.min(p.max(axis=0) - p.min(axis=0))))
+
+
+def _inside_depth(islands: list[trimesh.Trimesh], pts: np.ndarray) -> tuple[np.ndarray, float]:
+ """(mask of ``pts`` inside one of ``islands``, max distance of those to the surface).
Containment is the per-island, fixed-direction parity ray test the articulation gate
already uses (:func:`codeverse.spatial.joints_collide.inside_island`), NOT
@@ -150,30 +265,135 @@ def penetration_depth(a: trimesh.Trimesh, b: trimesh.Trimesh, n: int = N_SAMPLES
(open shells, boolean leftovers, mirrored halves, single-sided planes); only the
mixed closed/open case still fired, which is why the shipped tests stayed green.
Islands that are not watertight are tested the same way and the answer is
- approximate — the same trade joints_collide.penetration documents and flags.
- """
- rng = np.random.default_rng(_RNG_SEED)
- worst_depth, worst_frac = 0.0, 0.0
- for src, dst in ((a, b), (b, a)):
- pts = _sample(src, n, rng)
- inside = np.zeros(len(pts), dtype=bool)
- depth = 0.0
- for island in oriented_islands(dst):
- try:
- hit = inside_island(island, pts)
- except Exception: # noqa: BLE001 - a degenerate island must not fail the gate
- continue
- if not hit.any():
- continue
- _, dist, _ = trimesh.proximity.closest_point(island, pts[hit])
- depth = max(depth, float(np.max(dist)))
- inside |= hit
- frac = float(np.mean(inside)) if len(inside) else 0.0
- if frac <= 0.0:
+ approximate — the same trade joints_collide.penetration documents and flags."""
+ inside = np.zeros(len(pts), dtype=bool)
+ depth = 0.0
+ if len(pts) == 0:
+ return inside, depth
+ for island in islands:
+ try:
+ hit = inside_island(island, pts)
+ except Exception: # noqa: BLE001 - a degenerate island must not fail the gate
continue
- worst_depth = max(worst_depth, depth)
- worst_frac = max(worst_frac, frac)
- return worst_depth, worst_frac
+ if not hit.any():
+ continue
+ _, dist, _ = trimesh.proximity.closest_point(island, pts[hit])
+ depth = max(depth, float(np.max(dist)))
+ inside |= hit
+ return inside, depth
+
+
+def _in_box(pts: np.ndarray, lo: np.ndarray, hi: np.ndarray) -> np.ndarray:
+ return np.all((pts >= lo) & (pts <= hi), axis=1)
+
+
+def _faces_touching(mesh: trimesh.Trimesh, lo: np.ndarray, hi: np.ndarray) -> trimesh.Trimesh | None:
+ """The sub-mesh of faces whose bounds meet the box — what the region resample draws on."""
+ tri = mesh.triangles
+ mask = np.all(tri.max(axis=1) >= lo, axis=1) & np.all(tri.min(axis=1) <= hi, axis=1)
+ if not mask.any():
+ return None
+ sub = trimesh.Trimesh(vertices=mesh.vertices, faces=mesh.faces[mask], process=False)
+ return sub if float(sub.area) > 0.0 else None
+
+
+def _region_samples(src: trimesh.Trimesh, lo: np.ndarray, hi: np.ndarray, rng: np.random.Generator) -> np.ndarray:
+ """LOCAL_EXTRA_SAMPLES surface samples of ``src`` inside the box: its touching faces are
+ clipped by the box's six planes and sampled (rejection sampling of the unclipped faces
+ is the fallback when the clip fails or leaves nothing)."""
+ sub = _faces_touching(src, lo, hi)
+ if sub is None:
+ return np.zeros((0, 3), dtype=float)
+ try:
+ clipped = trimesh.intersections.slice_mesh_plane(
+ sub, plane_normal=np.vstack([np.eye(3), -np.eye(3)]), plane_origin=np.vstack([[lo] * 3, [hi] * 3]), cap=False)
+ if isinstance(clipped, trimesh.Trimesh) and len(clipped.faces) and float(clipped.area) > 0.0:
+ sub = clipped
+ except Exception: # noqa: BLE001 - a degenerate sub-mesh falls back to rejection sampling
+ pass
+ extra = _sample(sub, LOCAL_EXTRA_SAMPLES, rng)
+ return extra[_in_box(extra, lo, hi)]
+
+
+def _probe_direction(
+ name_src: str,
+ src: trimesh.Trimesh,
+ name_dst: str,
+ dst: trimesh.Trimesh,
+ cache: _PartCache,
+ pts: np.ndarray,
+ seeds: np.ndarray | None,
+ rng: np.random.Generator,
+) -> Penetration:
+ """``src``'s surface inside ``dst``: the whole-surface samples ``pts`` first, then a
+ dense pass on the region where the overlap actually is (around the inside samples,
+ the inside vertices and ``seeds``, grown by half the thinner part) — or on the whole
+ AABB overlap when it is too small to have caught LOCAL_MIN_SAMPLES samples."""
+ islands = cache.islands(name_dst)
+ lo = np.maximum(src.bounds[0], dst.bounds[0]) - _REGION_HAIR_M
+ hi = np.minimum(src.bounds[1], dst.bounds[1]) + _REGION_HAIR_M
+ hit, depth = _inside_depth(islands, pts)
+ frac = float(np.mean(hit)) if len(hit) else 0.0
+ verts = np.asarray(src.vertices, dtype=float)
+ verts = verts[_in_box(verts, lo, hi)]
+ if len(verts) > LOCAL_MAX_VERTICES:
+ verts = verts[np.linspace(0, len(verts) - 1, LOCAL_MAX_VERTICES).astype(int)]
+ hit_v, depth_v = _inside_depth(islands, verts)
+ depth = max(depth, depth_v)
+ # fcl's closest points of two intersecting Convex objects are (0, 0, 0): keep only seeds
+ # that lie in the AABB overlap
+ seeds = seeds[_in_box(seeds, lo, hi)] if seeds is not None and len(seeds) else np.zeros((0, 3))
+ found = np.vstack([pts[hit], verts[hit_v], seeds])
+ in_box = _in_box(pts, lo, hi)
+ thickness = cache.thickness(name_dst)
+ if len(found) == 0:
+ if int(in_box.sum()) >= LOCAL_MIN_SAMPLES:
+ return Penetration(name_src, name_dst, depth, frac, 0.0, 0, thickness)
+ region_lo, region_hi = lo, hi
+ else:
+ margin = max(PENETRATION_WARN_M, 0.5 * min(cache.thickness(name_src), thickness))
+ region_lo = np.minimum(np.maximum(lo, found.min(axis=0) - margin), hi)
+ region_hi = np.maximum(np.minimum(hi, found.max(axis=0) + margin), region_lo)
+ in_region = _in_box(pts, region_lo, region_hi)
+ inside, n_local = int(hit[in_region].sum()), int(in_region.sum())
+ if n_local < LOCAL_MIN_SAMPLES:
+ extra = _region_samples(src, region_lo, region_hi, rng)
+ hit_e, depth_e = _inside_depth(islands, extra)
+ depth = max(depth, depth_e)
+ inside += int(hit_e.sum())
+ n_local += len(extra)
+ return Penetration(name_src, name_dst, depth, frac, inside / n_local if n_local else 0.0, inside, thickness)
+
+
+def penetration_probe(
+ name_a: str,
+ a: trimesh.Trimesh,
+ name_b: str,
+ b: trimesh.Trimesh,
+ *,
+ cache: _PartCache | None = None,
+ seeds: np.ndarray | None = None,
+) -> Penetration:
+ """Mutual containment of ``a`` and ``b``, both directions; the deeper one is returned
+ with ``fraction_inside`` = the max over both. ``seeds`` are known overlap points (the
+ fcl closest points of a pair at distance 0) that localise the dense pass."""
+ cache = cache if cache is not None else _PartCache({name_a: a, name_b: b})
+ # the two whole-surface draws come first, in the pre-2026-08-30 order, so fraction_inside
+ # is the same number the corpus was scored with; the dense pass draws from its own stream
+ rng = np.random.default_rng(_RNG_SEED)
+ pts_a, pts_b = _sample(a, N_SAMPLES, rng), _sample(b, N_SAMPLES, rng)
+ ab = _probe_direction(name_a, a, name_b, b, cache, pts_a, seeds, rng)
+ ba = _probe_direction(name_b, b, name_a, a, cache, pts_b, seeds, rng)
+ worst = max(ab, ba, key=lambda p: (p.depth_m, p.inside_count))
+ return Penetration(worst.entering, worst.container, worst.depth_m, max(ab.fraction_inside, ba.fraction_inside),
+ worst.local_fraction, worst.inside_count, worst.thickness_m,
+ min(ab.own_through_ratio, ba.own_through_ratio))
+
+
+def penetration_depth(a: trimesh.Trimesh, b: trimesh.Trimesh) -> tuple[float, float]:
+ """(max depth, fraction of samples inside) of ``a``'s surface inside ``b`` and vice versa."""
+ p = penetration_probe("a", a, "b", b)
+ return p.depth_m, p.fraction_inside
def _fmt_vec(v: tuple[float, float, float]) -> str:
@@ -181,11 +401,11 @@ def _fmt_vec(v: tuple[float, float, float]) -> str:
return fmt_vec(v, 4)
-def _island_findings(name: str, mesh: trimesh.Trimesh) -> list[GateFinding]:
- try:
- islands = mesh.split(only_watertight=False)
- except Exception:
- return []
+def _mm(x: float) -> float:
+ return round(float(x) * 1000.0, 1)
+
+
+def _island_findings(name: str, mesh: trimesh.Trimesh, islands: list[trimesh.Trimesh]) -> list[GateFinding]:
if len(islands) <= 1:
return []
ext = float(np.max(mesh.extents))
@@ -201,6 +421,59 @@ def _island_findings(name: str, mesh: trimesh.Trimesh) -> list[GateFinding]:
return out
+def _penetration_finding(a: str, b: str, pen: Penetration, warn_m: float, error_m: float) -> GateFinding:
+ through = pen.through_ratio
+ # ERROR keeps the pre-2026-08-30 meaning — deep AND a visible share of the part
+ # (``PENETRATION_MIN_FRACTION``) — now with the depth measured properly. A pair found
+ # only by the dense local pass (a stile 17 mm through a seat slab, 1 % of either surface)
+ # is reported with every number but stays a WARN: with ERROR by depth alone the corpus
+ # re-run flipped 27 runs of such joinery pass→fail on a cap the eye cannot confirm; the
+ # judge, who sees the picture, is the one who can (D46 d). What still flips (14 of 217
+ # runs) is a pair the old gate already reported, now measured 9.4 → 11.3 mm deep.
+ sev = (Severity.ERROR if pen.depth_m > error_m and pen.fraction_inside >= PENETRATION_MIN_FRACTION
+ else Severity.WARN)
+ msg = (f"'{a}' and '{b}' interpenetrate by ≈{pen.depth_m * 1000:.1f} mm "
+ f"({pen.fraction_inside:.0%} of surface samples inside, {pen.local_fraction:.0%} where they meet)")
+ if through >= 0.5:
+ # the ratio saturates at the mid-plane: a tenon that STOPS there and a rail that passes
+ # clean through read the same, so the words say what was measured and no more
+ msg += (f" — '{pen.entering}' reaches {min(through, 1.0):.0%} of the way to the mid-plane of "
+ f"'{pen.container}' ({pen.thickness_m * 1000:.0f} mm thick)")
+ if through >= THROUGH_FAR_SIDE_RATIO:
+ hint = (f"'{pen.entering}' reaches the middle of '{pen.container}' — as far in as a surface can be "
+ f"measured: if it is meant to stop inside (a tenon), fine; if it should end at the surface, "
+ f"shorten it; if it is a continuous member (a stile through a seat), notch '{pen.container}' "
+ f"around it or accept the overlap (a hairline overlap is fine for welding)")
+ else:
+ hint = f"shrink or move '{a}'/'{b}' so they overlap by ≤ {warn_m * 1000:.0f} mm (a hairline overlap is fine for welding)"
+ return GateFinding(gate=GATE, severity=sev, target=a, message=msg, fix_hint=hint,
+ data={"kind": "penetration", "other": b, **pen.as_data()})
+
+
+def _ledger(
+ names: list[str],
+ parts: dict[str, trimesh.Trimesh],
+ edges: set[tuple[str, str]],
+ exact: dict[tuple[str, str], PairDistance],
+ overlaps: list[tuple[str, str, Penetration]],
+ planned: list[list[Any]],
+ unresolved: list[str],
+ gap_m: float,
+) -> GateFinding:
+ """The per-pair table ``check_connectivity`` used to compute and drop at exit: what
+ the judge payload needs to say "these are welds" without the VLM guessing."""
+ order = {n: i for i, n in enumerate(names)}
+ contacts = [[a, b, _mm(exact[(a, b)].distance)] for a, b in sorted(edges, key=lambda e: (order[e[0]], order[e[1]]))]
+ over = [[a, b, _mm(p.depth_m), round(p.through_ratio, 2)] for a, b, p in overlaps if _mm(p.depth_m) > 0.0]
+ return GateFinding(
+ gate=GATE, severity=Severity.INFO, target="",
+ message=f"contact ledger: {len(names)} parts, {len(contacts)} contacts, {len(over)} overlaps",
+ data={"kind": "ledger", "parts": list(names), "contact_gap_mm": _mm(gap_m), "contacts": contacts, "overlaps": over,
+ "ground_gap_mm": {n: _mm(float(parts[n].bounds[0][1])) for n in names},
+ "planned": planned, "planned_unresolved": unresolved},
+ )
+
+
def check_connectivity(
glb: Path | str,
*,
@@ -209,9 +482,13 @@ def check_connectivity(
penetration_warn_m: float = PENETRATION_WARN_M,
penetration_error_m: float = PENETRATION_ERROR_M,
language: str = "",
+ planned_edges: Sequence[PlannedEdge] = (),
) -> GateReport:
"""Run the connectivity gate on ``glb`` (see module docstring). ``language`` selects
- the frame of the translation hints (default: the GLB frame, labelled as such)."""
+ the frame of the translation hints (default: the GLB frame, labelled as such).
+ ``planned_edges`` are the plan's ``attach_to`` pairs: each is measured exactly and
+ listed in the ledger as contact/open; an open one is reported, not an ERROR — whether
+ a missed planned join fails the gate is the owner's call (not made, 2026-08-30)."""
t0 = time.time()
up = "z" if language_frame(language) is Frame.Z_UP_NEG_Y_FRONT else "y"
findings: list[GateFinding] = []
@@ -235,25 +512,31 @@ def check_connectivity(
# ---- pairwise distances (AABB prefilter) + penetration
edges: set[tuple[str, str]] = set()
exact: dict[tuple[str, str], PairDistance] = {}
- objs = _FclObjects(parts) # one BVH per part, built lazily, shared across pairs
+ overlaps: list[tuple[str, str, Penetration]] = []
+ cache = _PartCache(parts) # one BVH / island split / thickness per part, shared across pairs
for a, b in itertools.combinations(big, 2):
lower = _aabb_gap(parts[a], parts[b])
if lower > gap_m:
continue
- pd = pair_distance(a, parts[a], b, parts[b], obj_a=objs.get(a), obj_b=objs.get(b))
+ pd = pair_distance(a, parts[a], b, parts[b], obj_a=cache.fcl(a), obj_b=cache.fcl(b))
exact[(a, b)] = pd
if pd.distance <= gap_m:
edges.add((a, b))
if lower == 0.0: # AABBs overlap → possible penetration
- depth, frac = penetration_depth(parts[a], parts[b])
- if frac >= PENETRATION_MIN_FRACTION and depth > penetration_warn_m:
- sev = Severity.ERROR if depth > penetration_error_m else Severity.WARN
- findings.append(GateFinding(
- gate=GATE, severity=sev, target=a,
- message=f"'{a}' and '{b}' interpenetrate by ≈{depth * 1000:.1f} mm ({frac:.0%} of surface samples inside)",
- fix_hint=f"shrink or move '{a}'/'{b}' so they overlap by ≤ {penetration_warn_m * 1000:.0f} mm (a hairline overlap is fine for welding)",
- data={"other": b, "depth_m": depth, "fraction_inside": frac},
- ))
+ # at distance 0 fcl's closest points lie ON the overlap: a seed for the dense pass
+ seeds = np.array([pd.point_a, pd.point_b], dtype=float) if pd.distance <= 0.0 else None
+ if seeds is not None:
+ # two intersecting Convex objects give fcl nothing to report and it returns the
+ # ORIGIN as both closest points; a part centred on the origin would keep it as
+ # a seed and widen the dense region over nothing
+ seeds = seeds[np.any(seeds != 0.0, axis=1)]
+ seeds = seeds if len(seeds) else None
+ pen = penetration_probe(a, parts[a], b, parts[b], cache=cache, seeds=seeds)
+ if pen.depth_m > 0.0:
+ overlaps.append((a, b, pen))
+ dense = pen.inside_count >= PENETRATION_MIN_INSIDE and pen.local_fraction >= PENETRATION_MIN_LOCAL_FRACTION
+ if pen.depth_m > penetration_warn_m and (pen.fraction_inside >= PENETRATION_MIN_FRACTION or dense):
+ findings.append(_penetration_finding(a, b, pen, penetration_warn_m, penetration_error_m))
# ---- components → floating parts
comps = collide.components(big, edges)
# TOUCHING the ground, not merely at-or-below it: the old one-sided `<= gap_m`
@@ -287,9 +570,9 @@ def check_connectivity(
for n in big:
if n in support:
continue
- near = _nearest_supported(n, parts, support, exact, objs)
+ near = _nearest_supported(n, parts, support, exact, cache)
if near is None:
- findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=n,
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=n, data={"kind": "floating"},
message=f"part '{n}' is floating: touches nothing", fix_hint=f"attach '{n}' to a neighbouring part"))
continue
other = near.b if near.a == n else near.a
@@ -302,16 +585,49 @@ def check_connectivity(
message=f"part '{n}' is floating: nearest supported part is '{other}' at {near.distance * 1000:.1f} mm",
fix_hint=f"translate '{n}' by {_fmt_vec(vec)} m ({frame_label(language)}) — or extend it by "
f"{near.distance * 1000:.1f} mm towards '{other}' — so the surfaces touch",
- data={"nearest": other, "gap_m": near.distance, "gap_vector_m": list(vec), "frame": language_frame(language).value,
- "gap_vector_glb_m": list(vec_glb), "closest_point_self": list(p_self), "closest_point_other": list(p_other)},
+ data={"kind": "floating", "nearest": other, "gap_m": near.distance, "gap_vector_m": list(vec),
+ "frame": language_frame(language).value, "gap_vector_glb_m": list(vec_glb),
+ "closest_point_self": list(p_self), "closest_point_other": list(p_other)},
))
# ---- stray islands inside parts
for n in big:
- findings.extend(_island_findings(n, parts[n]))
+ findings.extend(_island_findings(n, parts[n], cache.islands(n)))
+ # ---- the plan's attach_to edges, measured whatever the AABB prefilter said
+ planned: list[list[Any]] = []
+ unresolved: list[str] = []
+ seen_pairs: set[frozenset[str]] = set()
+ for a, cands in planned_edges:
+ names_b = (cands,) if isinstance(cands, str) else tuple(cands)
+ if a not in parts:
+ if a not in unresolved:
+ unresolved.append(a)
+ continue
+ rows: list[list[Any]] = []
+ for b in names_b:
+ if b not in parts:
+ if b not in unresolved:
+ unresolved.append(b)
+ continue
+ if a == b or frozenset((a, b)) in seen_pairs:
+ continue
+ seen_pairs.add(frozenset((a, b)))
+ pd = exact.get((a, b)) or exact.get((b, a))
+ if pd is None:
+ pd = pair_distance(a, parts[a], b, parts[b], obj_a=cache.fcl(a), obj_b=cache.fcl(b))
+ exact[(a, b)] = pd
+ rows.append([a, b, _mm(pd.distance), "contact" if pd.distance <= gap_m else "open"])
+ # a group is ONE planned join offered against every parent copy the child's box
+ # touches (contract.planned_joins): the exact distances say which copy it meant —
+ # every CONTACT row, else the nearest OPEN one. Resolving the tie by list order
+ # printed "OPEN: Brace_1→Leg_0" for a join the plan never meant (skeptic 2026-08-30);
+ # reducing per CHILD instead hid a second, genuinely open join.
+ contacts = [r for r in rows if r[3] == "contact"]
+ planned.extend(contacts if contacts else rows[:1] if len(rows) <= 1 else [min(rows, key=lambda r: r[2])])
passed = not any(f.severity == Severity.ERROR for f in findings)
if passed and len(big) > 1:
findings.append(GateFinding(gate=GATE, severity=Severity.INFO,
message=f"all {len(big)} parts are connected ({len(edges)} contacts, gap ≤ {gap_m * 1000:.0f} mm)"))
+ findings.append(_ledger(names, parts, edges, exact, overlaps, planned, unresolved, gap_m))
return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
@@ -320,13 +636,13 @@ def _nearest_supported(
parts: dict[str, trimesh.Trimesh],
support: set[str],
exact: dict[tuple[str, str], PairDistance],
- objs: _FclObjects,
+ cache: _PartCache,
n_candidates: int = 3,
) -> PairDistance | None:
"""Exact distance from floating part ``n`` to its nearest supported part.
Candidates are ranked by AABB lower bound; the closest few get an exact test
- (reusing the per-part BVHs in ``objs``).
+ (reusing the per-part BVHs in ``cache``).
"""
if not support:
return None
@@ -335,7 +651,7 @@ def _nearest_supported(
for o in ranked:
pd = exact.get((n, o)) or exact.get((o, n))
if pd is None:
- pd = pair_distance(n, parts[n], o, parts[o], obj_a=objs.get(n), obj_b=objs.get(o))
+ pd = pair_distance(n, parts[n], o, parts[o], obj_a=cache.fcl(n), obj_b=cache.fcl(o))
exact[(n, o)] = pd
if best is None or pd.distance < best.distance:
best = pd
diff --git a/harness/codeverse/spatial/contract.py b/harness/codeverse/spatial/contract.py
index 1fc0ef0f..e8673e17 100644
--- a/harness/codeverse/spatial/contract.py
+++ b/harness/codeverse/spatial/contract.py
@@ -13,6 +13,9 @@ Severity policy (``tol = max(tol_m, REL_TOL × plan extent)`` per axis):
* bbox centre / extents off by > tol → WARN (exact delta in the hint);
> ``ERROR_FACTOR × tol`` → ERROR
* overall bbox vs ``overall_bbox`` → same policy
+* overall extents are the plan's with up swapped for a horizontal axis → ERROR
+ ``data["kind"] == "orientation"`` (lying down / stood on end); the two horizontal
+ extents swapped → WARN "turned" (the az-0 view then shows a side, not the front)
* not standing on the ground / footprint off-centre → WARN
* GLB parts the plan never mentioned → INFO
* ScenePlan: zone groups missing → WARN; model outside ``bounds`` → WARN
@@ -34,7 +37,14 @@ from codeverse.contracts.artifacts import (
Severity,
)
from codeverse.contracts.plan import BBox, PartPlan, Plan, ScenePlan, StaticPlan
-from codeverse.conventions import BBOX_TOLERANCE_M, LANGUAGE_FRAME, Frame, to_snake
+from codeverse.conventions import (
+ BBOX_TOLERANCE_M,
+ CONTACT_GAP_M,
+ FRAME_AXES,
+ LANGUAGE_FRAME,
+ Frame,
+ to_snake,
+)
from codeverse.spatial.measure import fmt_extent_cm, fmt_vec
GATE = "contract"
@@ -44,6 +54,30 @@ REL_TOL = 0.10
ERROR_FACTOR = 3.0
_AXES = ("x", "y", "z")
+# Orientation (2026-08-30). A 90° turn about a horizontal axis leaves the AABB of the
+# planned box with its up extent swapped for a horizontal one, so "lying down" is a
+# permutation test on extents — but planners size THIN axes badly (h2h c_clamp: 9.6 cm
+# planned for a 2.4 cm clamp), so only the planned LONG axis is required to reappear,
+# within ORIENT_FIT; the thin one may be over-planned by up to ORIENT_OVER (the h2h
+# clock: 26 cm planned, 34 cm real). The up extent itself must have shrunk by
+# ORIENT_LYING; a build merely too short (fancy_v1 chamber_organ, 1.15 m for 3.2 m
+# planned, nothing sideways) or a 2× scale error is contract_violation, not this.
+# "Stood on end" (taller than planned, the planned width now up) needs ORIENT_STOOD:
+# planners under-size tall objects — loop_w7 orrery 0.32 m planned / 0.47 m built and
+# fancy_v1 smock_windmill 18.5 / 25.8 m are upright and sit at 1.4–1.5×. The rotation
+# axis's own extent must not have moved by more than ORIENT_THIRD (sysprompt_ab
+# b36_v0_01r: a table 1.38 m wide for a 0.48 m chair — wrong object, not rotated), and
+# near-cubes say nothing (ORIENT_ANISO). Over every measured static_object round under
+# bench/out (629 measurements: 435 rounds + 194 final measurement.json, 217 runs) these
+# fire 0 times; on the brilliana c_clamp and gate_valve GLBs (both lying, by eye) they
+# fire with the right axis.
+ORIENT_FIT = float(np.log(1.25))
+ORIENT_LYING = float(np.log(1.5))
+ORIENT_STOOD = float(np.log(2.0))
+ORIENT_THIRD = float(np.log(1.5))
+ORIENT_ANISO = 1.5
+ORIENT_OVER = 1.4
+
# --------------------------------------------------------------------------- frames
def language_frame(language: str) -> Frame:
@@ -112,6 +146,49 @@ def match_parts(plan_parts: list[PartPlan], measured: list[PartMeasure]) -> tupl
return matched, list(remaining.values())
+def planned_joins(plan: Plan | None, measurement: Measurement | None) -> list[tuple[str, tuple[str, ...]]]:
+ """The plan's ``attach_to`` edges spelled in the GLB's part names, for the connectivity ledger.
+
+ The ONE resolver: the track's gate and the MCP ``check_connectivity`` / folded build
+ check all call this, so the agent-facing ledger and the judge's read the same pairs.
+ Names resolve the way ``check_contract`` resolves them (``match_parts``: the exact node
+ first, then the ``Name_0..N`` instances). Counted 2026-08-30 over the 357 stored
+ static_object rounds that carry attach_to edges: 965 of 2 666 raw plan names are
+ instance parts absent from the mesh under their plan spelling (``FrontLeg`` →
+ ``FrontLeg_0``/``FrontLeg_1``) — feeding raw names listed them as unresolved.
+ Each child copy joins the copy of its parent it TOUCHES by AABB (gap ≤ CONTACT_GAP_M),
+ and every touching copy when several do: a brace spanning Leg_1→Leg_3 whose box also
+ grazes Leg_0 ties at 0 for all three, and picking the first by list order sent it to
+ Leg_0 alone — a false OPEN. The gate measures every pair exactly and reduces per
+ child (the contact row wins, else the smallest gap), so emitting candidates costs
+ nothing but a guess. A child touching no copy joins the nearest one — the full cross
+ product would report the far apron/leg pair of every chair as OPEN.
+ """
+ if plan is None or measurement is None or not measurement.parts:
+ return []
+ parts = list(getattr(plan, "parts", []) or [])
+ matched, _ = match_parts(parts, measurement.parts)
+ edges: list[tuple[str, str]] = []
+ for pp in parts:
+ if not pp.attach_to:
+ continue
+ parents = matched.get(pp.attach_to) or []
+ for child in matched.get(pp.name) or []:
+ gaps = {p.name: _aabb_gap(child, p) for p in parents if p.name != child.name}
+ if not gaps:
+ continue
+ touching = [n for n, g in gaps.items() if g <= CONTACT_GAP_M]
+ edges.append((child.name, tuple(touching or [min(gaps, key=gaps.__getitem__)])))
+ return edges
+
+
+def _aabb_gap(a: PartMeasure, b: PartMeasure) -> float:
+ """Euclidean distance between two axis-aligned boxes (0 when they overlap)."""
+ lo_a, hi_a = np.asarray(a.bbox_min, dtype=float), np.asarray(a.bbox_max, dtype=float)
+ lo_b, hi_b = np.asarray(b.bbox_min, dtype=float), np.asarray(b.bbox_max, dtype=float)
+ return float(np.linalg.norm(np.maximum(np.maximum(lo_a - hi_b, lo_b - hi_a), 0.0)))
+
+
@dataclass
class _BoxDelta:
center: np.ndarray
@@ -168,6 +245,72 @@ def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, language:
return out
+def _log_ratio(a: float, b: float) -> float:
+ return abs(float(np.log(a / b)))
+
+
+def _orientation_finding(m: Measurement, plan: StaticPlan, language: str) -> GateFinding | None:
+ """Is the object lying down / stood on end (ERROR) or turned 90° about up (WARN)?
+
+ Everything is in the plan frame: ``meas`` is the measured overall extents mapped back
+ with :func:`glb_vec_to_plan`, ``up`` the frame's up axis from ``conventions``. One
+ finding at most; the thresholds and the corpus behind them are documented at the top."""
+ planned = np.asarray(plan.overall_bbox.extents, dtype=float)
+ meas = glb_vec_to_plan(m.extents, language, extents=True)
+ if np.any(planned <= 1e-6) or np.any(meas <= 1e-6):
+ return None
+ up = int(np.argmax(FRAME_AXES[language_frame(language)]["up"]))
+ label = frame_label(language)
+ horizontal = [a for a in range(3) if a != up]
+ best: tuple[float, str, int] | None = None # (fit, pose, h)
+ for h in horizontal:
+ k = 3 - up - h # the axis the object turned about keeps its extent
+ if _log_ratio(meas[k], planned[k]) > ORIENT_THIRD:
+ continue
+ shrink = _log_ratio(meas[up], planned[up])
+ if meas[up] < planned[up] and shrink >= ORIENT_LYING and planned[up] / planned[h] >= ORIENT_ANISO:
+ fit = _log_ratio(meas[h], planned[up]) # the planned height now runs along h
+ if fit <= ORIENT_FIT and meas[up] <= planned[h] * ORIENT_OVER and (best is None or fit < best[0]):
+ best = (fit, "lying", h)
+ elif meas[up] > planned[up] and shrink >= ORIENT_STOOD and planned[h] / planned[up] >= ORIENT_ANISO:
+ fit = _log_ratio(meas[up], planned[h]) # the planned h extent now runs up
+ if fit <= ORIENT_FIT and meas[h] <= planned[up] * ORIENT_OVER and (best is None or fit < best[0]):
+ best = (fit, "stood", h)
+ data = {"kind": "orientation", "planned_up_m": float(planned[up]), "measured_up_m": float(meas[up]),
+ "frame": language_frame(language).value}
+ if best is not None:
+ _, pose, h = best
+ k = 3 - up - h
+ # a disagreement with the PLANNED box, phrased as one: a plan that boxed a wall clock
+ # flat makes an upright build read "stood", and the judge treats ERROR text as fact
+ verb = "is lying down relative to the planned box" if pose == "lying" else "stands on end relative to the planned box"
+ return GateFinding(
+ gate=GATE, severity=Severity.ERROR, target="overall",
+ message=f"object {verb}: planned {planned[up] * 100:.1f} cm tall ({_AXES[up]}), measured "
+ f"{meas[up] * 100:.1f} cm tall with {planned[h] * 100:.1f} cm along {_AXES[h]} planned "
+ f"and {meas[h] * 100:.1f} cm measured — the {_AXES[up]} and {_AXES[h]} extents are swapped",
+ fix_hint=f"rotate the whole object 90° about {_AXES[k]} so its height runs along {_AXES[up]} "
+ f"({label}); do not resize parts to fit the box",
+ data={**data, "best_axis": _AXES[h], "pose": pose},
+ )
+ h1, h2 = horizontal
+ if (_log_ratio(meas[up], planned[up]) <= ORIENT_THIRD
+ and max(planned[h1] / planned[h2], planned[h2] / planned[h1]) >= ORIENT_ANISO
+ and _log_ratio(meas[h1], planned[h2]) <= ORIENT_FIT and _log_ratio(meas[h2], planned[h1]) <= ORIENT_FIT
+ and _log_ratio(meas[h1], planned[h1]) >= ORIENT_LYING and _log_ratio(meas[h2], planned[h2]) >= ORIENT_LYING):
+ wide = h1 if planned[h1] > planned[h2] else h2
+ return GateFinding(
+ gate=GATE, severity=Severity.WARN, target="overall",
+ message=f"object is turned 90° about {_AXES[up]}: planned {planned[h1] * 100:.1f}×{planned[h2] * 100:.1f} cm "
+ f"({_AXES[h1]}×{_AXES[h2]}), measured {meas[h1] * 100:.1f}×{meas[h2] * 100:.1f} cm — its front "
+ f"faces sideways in the az-0 view",
+ fix_hint=f"rotate the whole object 90° about {_AXES[up]} so the {planned[wide] * 100:.1f} cm side runs "
+ f"along {_AXES[wide]} ({label})",
+ data={**data, "best_axis": _AXES[wide], "pose": "turned"},
+ )
+ return None
+
+
# --------------------------------------------------------------------------- gate
def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: float) -> list[GateFinding]:
findings: list[GateFinding] = []
@@ -209,6 +352,8 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: f
ob = plan_bbox_to_glb(plan.overall_bbox, language)
d = _box_delta(np.asarray(m.bbox_min), np.asarray(m.bbox_max), ob, tol_m)
findings.extend(_box_findings("overall", d, ob, what="overall", language=language))
+ if (orient := _orientation_finding(m, plan, language)) is not None:
+ findings.append(orient)
# ground + footprint
if abs(m.ground_gap_m) > tol_m:
where = "above" if m.ground_gap_m > 0 else "below"
diff --git a/harness/codeverse/spatial/measure.py b/harness/codeverse/spatial/measure.py
index 82d9c971..cbc8bbc0 100644
--- a/harness/codeverse/spatial/measure.py
+++ b/harness/codeverse/spatial/measure.py
@@ -20,9 +20,11 @@ never a reason for a measurement to fail.
from __future__ import annotations
import contextlib
+import json
import re
+import struct
import threading
-from collections import OrderedDict
+from collections import Counter, OrderedDict
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -66,6 +68,49 @@ def load_scene(glb: Path | str) -> trimesh.Scene:
return scene
+def gltf_node_names(glb: Path | str) -> list[str | None]:
+ """The ``name`` of every node in the GLB's JSON chunk, in index order (None = unnamed)."""
+ with Path(glb).open("rb") as fh:
+ head = fh.read(20)
+ if len(head) < 20 or head[:4] != b"glTF":
+ return []
+ (n,) = struct.unpack("<I", head[12:16])
+ try:
+ js = json.loads(fh.read(n))
+ except ValueError:
+ return []
+ return [node.get("name") for node in js.get("nodes", [])]
+
+
+def node_name_findings(glb: Path | str) -> list[str]:
+ """Findings for a GLB whose node names trimesh cannot key on.
+
+ trimesh names graph nodes by their glTF ``name`` and de-duplicates collisions, and
+ on THREE.GLTFExporter files with repeated / missing names (the brilliana gallery's
+ desk-lamp-q2: 21 unnamed, 'Arm' x2, 'Shade' x2, 'Rivet' x4) that walk went wrong in
+ two ways at once — the root ``pivot`` matrix was dropped from its descendants and a
+ renamed 'Arm' was re-parented to the world, so an upright lamp measured as lying on
+ its side with a part 28 mm under the floor (2026-08-30). The harness's own exporters
+ name every node uniquely (blender, cadquery, and export_glb.mjs bake instances to
+ ``<Name>_<i>``: 0 of 14 recorded threejs GLBs differ from the naive bounds), so this
+ fires on foreign files and on an agent that reused a name — either way the numbers
+ downstream are approximate and the reader is told."""
+ names = gltf_node_names(glb)
+ if not names:
+ return []
+ out: list[str] = []
+ unnamed = sum(1 for n in names if not n)
+ dups = {n: c for n, c in Counter(n for n in names if n).items() if c > 1}
+ if unnamed:
+ out.append(f"{unnamed} of {len(names)} glTF nodes are unnamed — parts are keyed by node name; "
+ "measurements and contact checks may mis-pose them")
+ if dups:
+ shown = ", ".join(f"'{n}' x{c}" for n, c in sorted(dups.items())[:6])
+ out.append(f"duplicate glTF node names ({shown}) — trimesh re-parents renamed nodes; "
+ "measurements and contact checks may mis-pose them")
+ return out
+
+
def _subtree_nodes(scene: trimesh.Scene, root: str) -> list[str]:
"""All nodes under ``root`` (inclusive), depth first; cycle-safe (a malformed
graph, e.g. a node named like the base frame, must not hang the gate)."""
@@ -81,10 +126,36 @@ def _subtree_nodes(scene: trimesh.Scene, root: str) -> list[str]:
return out
+def world_transform(scene: trimesh.Scene, node: str) -> np.ndarray:
+ """``node``'s world matrix, composed by walking the edge matrices up to the base frame.
+
+ Not ``scene.graph.get(node)``: trimesh 4.12 leaves the SCENE-ROOT node's own matrix out
+ of its descendants' world transforms. A GLB whose root node carries the Z-up→Y-up
+ rotation — what THREE.GLTFExporter writes for a Z-up scene (``pivot``, the brilliana
+ gallery) — therefore measured as lying on its side: desk-lamp-q2 bounds y ∈ [−0.12, 0.12],
+ z ∈ [0, 0.45] from trimesh against y ∈ [0, 0.45] from the node walk and from the render
+ rig (2026-08-30). Every gate downstream — bbox, ground gap, floating, orientation —
+ read that wrong pose, and the judge read the gate text. Cycle-safe (a malformed graph
+ must not hang the gate)."""
+ edges = scene.graph.transforms.edge_data
+ parents = scene.graph.transforms.parents
+ m = np.eye(4)
+ seen: set[str] = set()
+ while node != scene.graph.base_frame and node in parents and node not in seen:
+ seen.add(node)
+ parent = parents[node]
+ local = edges.get((parent, node), {}).get("matrix")
+ if local is not None:
+ m = np.asarray(local, dtype=float) @ m
+ node = parent
+ return m
+
+
def _world_mesh(scene: trimesh.Scene, node: str) -> trimesh.Trimesh | None:
"""Geometry at ``node`` transformed to world space (None if not a mesh)."""
try:
- transform, geom_name = scene.graph.get(node)
+ _, geom_name = scene.graph.get(node)
+ transform = world_transform(scene, node)
except Exception:
return None
if geom_name is None:
@@ -278,6 +349,7 @@ def measure_glb(glb: Path | str) -> Measurement:
scene = load_scene(p)
parts = entry.parts if entry is not None and entry.parts is not None else part_meshes(scene)
m = _measure(scene, parts)
+ m.extra["findings"] = [*node_name_findings(p), *m.extra.get("findings", [])]
if entry is not None:
if entry.parts is None:
entry.parts = parts
diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.py
index c02902d4..f8ee6ed6 100644
--- a/harness/codeverse/spatial/tools.py
+++ b/harness/codeverse/spatial/tools.py
@@ -23,6 +23,7 @@ from codeverse.contracts.spec import Spec
from codeverse.conventions import OBJECT_VIEWS, OBJECT_VIEWS_QUICK
from codeverse.spatial.connectivity import check_connectivity as _check_connectivity
from codeverse.spatial.contract import check_contract as _check_contract
+from codeverse.spatial.contract import planned_joins
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
@@ -139,10 +140,11 @@ def _folded_checks(ctx: ToolContext, glb: Path, m: Measurement, language: str) -
numbers[f"{name.lower()}_errors"] = n_err
verdicts.append(f"{name.lower()} " + ("PASS" if report.passed else f"FAIL ({n_err} error(s))"))
- conn = _check_connectivity(glb, language=language)
+ plan = load_plan(ws.plan_path) if ws.plan_path.is_file() else None
+ conn = _check_connectivity(glb, language=language, planned_edges=planned_joins(plan, m))
fold("CONNECTIVITY", conn)
- if ws.plan_path.is_file():
- contract = _check_contract(m, load_plan(ws.plan_path), language=language)
+ if plan is not None:
+ contract = _check_contract(m, plan, language=language)
fold("CONTRACT", contract)
passed = conn.passed and contract.passed
else:
@@ -269,7 +271,12 @@ def measure(ctx: ToolContext, args: MeasureArgs) -> Observation:
@tool("check_connectivity", NoArgs, "Contact graph of all parts: floating parts (with the exact gap vector to close), interpenetration, stray islands.")
def check_connectivity(ctx: ToolContext, args: NoArgs) -> Observation:
glb = glb_path(ctx)
- report = _check_connectivity(glb, language=language_of(ctx))
+ plan = load_plan(ctx.workspace.plan_path) if ctx.workspace.plan_path.is_file() else None
+ try: # the plan's attach_to pairs in the GLB's part names — the same resolver as the track's gate
+ planned = planned_joins(plan, measure_glb(glb)) if plan is not None else []
+ except GlbLoadError as e:
+ return Observation.error(f"check_connectivity: {e}")
+ report = _check_connectivity(glb, language=language_of(ctx), planned_edges=planned)
ctx.workspace.write_json(ctx.workspace.gates_dir(ctx.round_index) / "connectivity_tool.json", report)
return gate_observation(report)
diff --git a/harness/codeverse/tracks/common.py b/harness/codeverse/tracks/common.py
index fbbe0bcf..2df1eb78 100644
--- a/harness/codeverse/tracks/common.py
+++ b/harness/codeverse/tracks/common.py
@@ -80,9 +80,13 @@ class Services:
def measure(self, glb: Path) -> Measurement:
return _import("codeverse.spatial.measure", "measure_glb")(glb)
- def connectivity(self, glb: Path, language: str = "") -> GateReport:
- """``language`` selects the frame of the fix hints (the author's frame, not the GLB's)."""
- return _import("codeverse.spatial.connectivity", "check_connectivity")(glb, language=language)
+ def connectivity(self, glb: Path, language: str = "", planned_edges: Sequence[tuple[str, str | Sequence[str]]] = ()) -> GateReport:
+ """``language`` selects the frame of the fix hints (the author's frame, not the GLB's);
+ ``planned_edges`` are the plan's attach_to pairs spelled in GLB part names — the gate
+ measures each one and lists it contact/open in its contact ledger (the judge's
+ assembly_fit ground truth since 2026-08-30)."""
+ return _import("codeverse.spatial.connectivity", "check_connectivity")(
+ glb, language=language, planned_edges=tuple(planned_edges))
def contract(self, measurement: Measurement, plan: Plan, tol_m: float, language: str = "") -> GateReport:
return _import("codeverse.spatial.contract", "check_contract")(measurement, plan, language=language, tol_m=tol_m)
diff --git a/harness/codeverse/tracks/static_object.py b/harness/codeverse/tracks/static_object.py
index 7ca0753b..e436cef1 100644
--- a/harness/codeverse/tracks/static_object.py
+++ b/harness/codeverse/tracks/static_object.py
@@ -34,6 +34,7 @@ from codeverse.conventions import (
)
from codeverse.orchestrator import DETAIL_KIND, RefineTask, TaskGroup, compact_instructions
from codeverse.prompts import render
+from codeverse.spatial.contract import planned_joins
from codeverse.tracks.common import RunContext
from codeverse.tracks.depth import (
PartScope,
@@ -81,9 +82,9 @@ class ObjectPipeline:
out: list[GateReport] = []
glb = Path(build.glb_path) if build.glb_path else None
if glb is not None:
- out.append(
- ctx.services.connectivity(glb, ctx.language.value)
- ) # fix hints in the author's frame
+ out.append( # fix hints in the author's frame; planned joins measured into the ledger
+ ctx.services.connectivity(glb, ctx.language.value, planned_edges=planned_joins(ctx.plan, measurement))
+ )
if measurement is not None and ctx.plan is not None:
out.append(
ctx.services.contract(measurement, ctx.plan, BBOX_TOLERANCE_M, ctx.language.value)
@@ -163,6 +164,12 @@ class ObjectPipeline:
build: BuildResult,
gates: list[GateReport],
) -> str:
+ """Nothing beyond ``gates_section``. The measured-structure block the judge reads
+ (contacts, planned joins, floor gaps, the weld line) is rendered by
+ ``judges.prompt_builder.gates_section`` from the connectivity report's contact
+ ledger — the report is stored in ``rounds/rNN.json``, so ``3dcv judge <slug>``,
+ calibration and every other reader of the round record get the same block as the
+ in-run judge without this method restating it (2026-08-30)."""
return ""
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
index 43ccb430..ae6e1259 100644
--- a/harness/tests/orchestrator_tracks/fakes.py
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -270,6 +270,7 @@ class FakeServices(Services):
self.reference_judges: list[tuple[str, int, str]] = []
self.silhouette_calls: list[tuple[str, str]] = []
self.connectivity_languages: list[str] = []
+ self.planned_edges: list[list[tuple[str, str]]] = []
self.geometry_renders: list[str] = []
def chat_model(self, model_id: str) -> Any:
@@ -326,8 +327,9 @@ class FakeServices(Services):
center=tuple(cen), tri_count=sum(p.tri_count for p in parts), n_meshes=len(parts), n_islands=len(parts),
parts=parts, ground_gap_m=float(bounds[0][1]), footprint_offset_m=float(np.hypot(cen[0], cen[2])))
- def connectivity(self, glb: Path, language: str = "") -> GateReport:
+ def connectivity(self, glb: Path, language: str = "", planned_edges: Sequence[tuple[str, str]] = ()) -> GateReport:
self.connectivity_languages.append(language)
+ self.planned_edges.append(list(planned_edges))
return GateReport(gate="connectivity", passed=True)
def contract(self, measurement: Measurement, plan: Plan, tol_m: float, language: str = "") -> GateReport:
diff --git a/harness/tests/orchestrator_tracks/test_static_judge_context.py b/harness/tests/orchestrator_tracks/test_static_judge_context.py
new file mode 100644
index 00000000..17f2ba8c
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_static_judge_context.py
@@ -0,0 +1,65 @@
+"""The static track hands the plan's attach_to pairs to the connectivity gate, spelled in the
+GLB's part names, so the gate's contact ledger can list each planned join as contact/open
+(the judge's assembly_fit ground truth, ``prompt_builder.gates_section``)."""
+
+from __future__ import annotations
+
+from codeverse.contracts.artifacts import Measurement, PartMeasure
+from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse.spatial.contract import planned_joins
+from codeverse.tracks.static_object import ObjectPipeline
+from tests.orchestrator_tracks.test_integrations2 import _static_run
+
+
+def _measurement(parts: dict[str, tuple[tuple[float, float, float], tuple[float, float, float]]]) -> Measurement:
+ rows = [PartMeasure(name=n, bbox_min=lo, bbox_max=hi) for n, (lo, hi) in parts.items()]
+ return Measurement(bbox_min=(0, 0, 0), bbox_max=(1, 1, 1), extents=(1, 1, 1), center=(0.5, 0.5, 0.5),
+ tri_count=12 * len(rows), n_meshes=len(rows), n_islands=len(rows), parts=rows)
+
+
+def test_track_passes_attach_to_pairs_to_the_connectivity_gate(tmp_path, chair_plan, settings):
+ _rec, _ws, _judge, services = _static_run(tmp_path, chair_plan, settings)
+ # the fake build exports one node per plan part under the plan's own name (no instance copies)
+ assert services.planned_edges == [[("FrontLeg", ("Seat",)), ("BackLeg", ("Seat",)), ("Backrest", ("BackLeg",)), ("Armrest", ("BackLeg",))]]
+
+
+def test_planned_joins_spell_instances_as_the_glb_does_and_pair_every_touching_parent_copy(chair_plan):
+ """Counted 2026-08-30 over the 342 stored static rounds with attach_to edges: 823 of 2 568
+ edges name an instance part (``FrontLeg`` for ``FrontLeg_0``/``FrontLeg_1``). Each child copy
+ joins every copy of its parent it touches (the backrest spans both back legs), else the
+ nearest — the cross product would call the far apron/leg pair of every chair OPEN."""
+ leg = lambda x, z: ((x - 0.02, 0.0, z - 0.02), (x + 0.02, 0.41, z + 0.02)) # noqa: E731
+ m = _measurement({
+ "Seat": ((-0.21, 0.41, -0.2), (0.21, 0.45, 0.2)),
+ "FrontLeg_0": leg(0.17, 0.16), "FrontLeg_1": leg(-0.17, 0.16),
+ "BackLeg_0": ((0.15, 0.0, -0.18), (0.19, 0.82, -0.14)), "BackLeg_1": ((-0.19, 0.0, -0.18), (-0.15, 0.82, -0.14)),
+ "Backrest": ((-0.2, 0.66, -0.185), (0.2, 0.78, -0.155)),
+ "Armrest_0": ((0.18, 0.635, -0.17), (0.22, 0.665, 0.18)), "Armrest_1": ((-0.22, 0.635, -0.17), (-0.18, 0.665, 0.18)),
+ })
+ edges = planned_joins(chair_plan, m)
+ assert edges == [('FrontLeg_0', ('Seat',)), ('FrontLeg_1', ('Seat',)), ('BackLeg_0', ('Seat',)), ('BackLeg_1', ('Seat',)), ('Backrest', ('BackLeg_0', 'BackLeg_1')), ('Armrest_0', ('BackLeg_0',)), ('Armrest_1', ('BackLeg_1',))]
+ assert "BackLeg_1" not in dict(edges)["Armrest_0"]
+
+
+def test_planned_joins_drop_what_the_mesh_does_not_have():
+ plan = StaticPlan(
+ object_name="Stool", summary="a stool", overall_bbox=BBox(center=(0, 0.2, 0), extents=(0.3, 0.4, 0.3)),
+ parts=[PartPlan(name="Top", role="top", description="disc", bbox=BBox(center=(0, 0.39, 0), extents=(0.3, 0.02, 0.3))),
+ PartPlan(name="Leg", role="leg", description="rod", bbox=BBox(center=(0, 0.19, 0), extents=(0.03, 0.38, 0.03)), attach_to="Top", instances=3),
+ PartPlan(name="Ring", role="ring", description="brace", bbox=BBox(center=(0, 0.1, 0), extents=(0.2, 0.02, 0.2)), attach_to="Leg")])
+ boxes = {"Top": ((-0.15, 0.38, -0.15), (0.15, 0.4, 0.15)), "Leg_0": ((-0.1, 0, -0.1), (-0.07, 0.38, -0.07)),
+ "Leg_1": ((0.07, 0, -0.1), (0.1, 0.38, -0.07)), "Ring": ((-0.1, 0.09, -0.1), (0.1, 0.11, 0.1))}
+ # two of three leg copies built; the ring's box overlaps both, so both are candidates for the gate to measure
+ assert planned_joins(plan, _measurement(boxes)) == [('Leg_0', ('Top',)), ('Leg_1', ('Top',)), ('Ring', ('Leg_0', 'Leg_1'))]
+ del boxes["Top"] # the parent never made it into the export: no edge, the contract gate reports the missing part
+ assert planned_joins(plan, _measurement(boxes)) == [('Ring', ('Leg_0', 'Leg_1'))]
+ assert planned_joins(None, _measurement(boxes)) == [] and planned_joins(plan, None) == []
+
+
+def test_judge_context_stays_empty_because_the_block_lives_in_gates_section(tmp_path, chair_plan):
+ """The block is rendered from the stored GateReport, so ``3dcv judge <slug>`` on a recorded
+ round gets it too; a judge_context copy would be a second source of the same facts."""
+ from codeverse.contracts.artifacts import BuildResult
+ from codeverse.workspace import Workspace
+
+ assert ObjectPipeline().judge_context(Workspace(tmp_path / "w"), chair_plan, 0, BuildResult(ok=True, language="threejs"), []) == ""
diff --git a/harness/tests/spatial_tools/test_connectivity.py b/harness/tests/spatial_tools/test_connectivity.py
index 62b5d944..3e6e7f40 100644
--- a/harness/tests/spatial_tools/test_connectivity.py
+++ b/harness/tests/spatial_tools/test_connectivity.py
@@ -7,7 +7,14 @@ import pytest
import trimesh
from codeverse.contracts.artifacts import Severity
-from codeverse.spatial.connectivity import check_connectivity, pair_distance, penetration_depth
+from codeverse.spatial.connectivity import (
+ PENETRATION_ERROR_M,
+ PENETRATION_MIN_FRACTION,
+ THROUGH_FAR_SIDE_RATIO,
+ check_connectivity,
+ pair_distance,
+ penetration_depth,
+)
from tests.spatial_tools.conftest import FLOAT_GAP_M
@@ -65,6 +72,10 @@ def test_penetration_is_flagged(tmp_path: Path) -> None:
pen = [f for f in r.findings if "interpenetrate" in f.message]
assert pen and pen[0].severity == Severity.ERROR
assert pen[0].data["depth_m"] == pytest.approx(0.03, abs=0.004)
+ assert pen[0].data["kind"] == "penetration" and {pen[0].target, pen[0].data["other"]} == {"A", "B"}
+ assert {"depth_m", "fraction_inside", "local_fraction", "inside_count", "through_ratio", "thickness_m",
+ "container", "entering"} <= set(pen[0].data)
+ assert pen[0].data["thickness_m"] == pytest.approx(0.2, abs=1e-6)
def test_hairline_overlap_is_fine(tmp_path: Path) -> None:
@@ -237,3 +248,158 @@ def test_a_model_authored_below_the_floor_still_reports_its_floating_part(tmp_pa
assert any("touches the ground" in f.message for f in sunk.findings)
+def _scene(path: Path, **meshes: trimesh.Trimesh) -> Path:
+ sc = trimesh.Scene()
+ for name, m in meshes.items():
+ sc.add_geometry(m, node_name=name, geom_name=name)
+ path.write_bytes(sc.export(file_type="glb"))
+ return path
+
+
+def _cylinder_y(radius: float, height: float, center: tuple[float, float, float]) -> trimesh.Trimesh:
+ m = trimesh.creation.cylinder(radius=radius, height=height, sections=32)
+ m.apply_transform(trimesh.transformations.rotation_matrix(np.pi / 2, (1, 0, 0)))
+ m.apply_translation(center)
+ return m
+
+
+def _penetrations(r) -> list:
+ return [f for f in r.findings if f.data.get("kind") == "penetration"]
+
+
+def _ledger(r):
+ led = [f for f in r.findings if f.message.startswith("contact ledger")]
+ assert len(led) == 1 and led[0].severity == Severity.INFO and led[0].target == ""
+ return led[0]
+
+
+def test_thin_rod_through_a_plate_is_measured_and_named_but_severity_stays_on_depth(tmp_path: Path) -> None:
+ """An 8 mm rod, 1 m long, standing through a 10 mm plate. The overlap band is ~1 % of
+ the rod's surface, under PENETRATION_MIN_FRACTION, and its deepest point is 5 mm, under
+ PENETRATION_ERROR_M — so the 4ddde32 gate said nothing on this GLB (verified against
+ the committed module, 2026-08-30). The dense local pass finds it and the through-ratio
+ says the rod reaches the plate's far side — as a MEASUREMENT: it is a WARN, because the
+ same number is what a stile through a seat or a boom seated in a mast reads, and the
+ picture, not the gate, decides whether that is a defect (corpus re-run: a 0.9 ERROR line
+ flipped 9 runs of designed joinery)."""
+ rod = _cylinder_y(0.004, 1.0, (0, 0.5, 0))
+ plate = trimesh.creation.box(extents=(0.3, 0.01, 0.3))
+ plate.apply_translation((0, 0.505, 0))
+
+ r = check_connectivity(_scene(tmp_path / "rod_plate.glb", Rod=rod, Plate=plate))
+
+ pen = _penetrations(r)
+ assert len(pen) == 1 and pen[0].severity == Severity.WARN and r.passed
+ d = pen[0].data
+ assert d["fraction_inside"] < PENETRATION_MIN_FRACTION, "the old floor would have silenced this"
+ assert d["depth_m"] < PENETRATION_ERROR_M, "depth alone keeps it a WARN"
+ assert d["depth_m"] == pytest.approx(0.005, abs=0.0005)
+ assert d["inside_count"] >= 4 and d["local_fraction"] >= 0.2
+ assert d["through_ratio"] >= THROUGH_FAR_SIDE_RATIO
+ assert d["entering"] == "Rod" and d["container"] == "Plate" and d["thickness_m"] == pytest.approx(0.01, abs=1e-6)
+ assert "reaches 93% of the way to the mid-plane of 'Plate' (10 mm thick)" in pen[0].message
+ assert "middle of 'Plate'" in pen[0].fix_hint and "shorten it" in pen[0].fix_hint
+ # the ledger carries the same pair with the same numbers, rounded
+ over = _ledger(r).data["overlaps"]
+ assert len(over) == 1 and set(over[0][:2]) == {"Rod", "Plate"}
+ assert over[0][2:] == [pytest.approx(5.0, abs=0.5), pytest.approx(d["through_ratio"], abs=0.01)]
+
+
+def test_a_designed_socket_stays_a_warn_with_a_low_through_ratio(tmp_path: Path) -> None:
+ """A branch neck seated 3 mm into a pipe block (pipe_tee's BranchPipeNeck x MainPipeRun):
+ above the 2 mm WARN line, nowhere near the far side of anything — WARN, and the message
+ does not talk about reaching through."""
+ pipe = trimesh.creation.box(extents=(0.3, 0.1, 0.1))
+ pipe.apply_translation((0, 0.05, 0))
+ neck = _cylinder_y(0.02, 0.1, (0, 0.1 - 0.003 + 0.05, 0))
+
+ r = check_connectivity(_scene(tmp_path / "socket.glb", MainPipeRun=pipe, BranchNeck=neck))
+
+ pen = _penetrations(r)
+ assert r.passed and len(pen) == 1 and pen[0].severity == Severity.WARN
+ d = pen[0].data
+ assert d["depth_m"] == pytest.approx(0.003, abs=0.0005)
+ assert d["through_ratio"] < 0.2
+ assert "reaches" not in pen[0].message and "where they meet" in pen[0].message
+
+
+def test_a_thin_part_sunk_into_a_thick_one_is_not_through(tmp_path: Path) -> None:
+ """h2h_microscope's FieldIlluminator: a 5 mm disc sunk 2.3 mm into the base. Measured
+ one way, the base's top surface reaches 82 % of the way through the disc; the pair's
+ through-ratio is the min over both directions, so a designed inset stays 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
+
+
+def test_contact_ledger_carries_contacts_overlaps_and_ground_gaps(tmp_path: Path) -> None:
+ """The 1 mm weld of test_hairline_overlap_is_fine is below the WARN line — no finding —
+ but the judge payload needs to know it is there to call it a weld, so the INFO ledger
+ lists it, with the contact and every part's height above the ground."""
+ 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 prefilter
+ never measures — a planned join is measured anyway and reported open, not as an ERROR
+ (whether it should fail the gate is the owner's call); a name the GLB does not have is
+ listed unresolved."""
+ r = check_connectivity(solid_stool_glb, planned_edges=[("Leg_0", "Seat"), ("Leg_0", "Leg_1"), ("Leg_0", "Ghost")])
+
+ assert r.passed
+ d = _ledger(r).data
+ assert d["planned"] == [["Leg_0", "Seat", 0.0, "contact"], ["Leg_0", "Leg_1", pytest.approx(260.0, abs=0.5), "open"]]
+ assert d["planned_unresolved"] == ["Ghost"]
+ assert sorted(d["parts"]) == ["Leg_0", "Leg_1", "Leg_2", "Leg_3", "Seat"]
+ assert len(d["contacts"]) == 4 and all(c[1] == "Seat" or c[0] == "Seat" for c in d["contacts"])
+
+
+def test_a_deep_overlap_only_the_dense_pass_can_see_is_a_warn_with_every_number(tmp_path: Path) -> None:
+ """A 40 mm square stile driven 17 mm into a 0.45 m seat slab — the corpus's commonest new
+ finding (rear stiles through seats on 14 dining chairs). The overlap is ~1 % of either
+ surface, so the 4ddde32 gate never saw it; the dense pass measures it, but a member the
+ eye cannot see inside a slab must not cap the run at 0.7 on its own: WARN, depth and
+ through-ratio in data, and the judge decides from the picture (D46 d)."""
+ seat = trimesh.creation.box(extents=(0.45, 0.036, 0.45))
+ seat.apply_translation((0, 0.45, 0)) # underside at y = 0.432
+ stile = trimesh.creation.box(extents=(0.03, 1.0, 0.03)) # a 1 m backrest post
+ stile.apply_translation((0.2, 0.432 + 0.017 - 0.5, 0.2)) # its top 17 mm inside the slab
+ r = check_connectivity(_scene(tmp_path / "stile_seat.glb", Seat=seat, Stile=stile))
+
+ pen = _penetrations(r)
+ assert len(pen) == 1
+ d = pen[0].data
+ assert d["depth_m"] > PENETRATION_ERROR_M, "deep — the old ERROR line by depth"
+ assert d["fraction_inside"] < PENETRATION_MIN_FRACTION, "…but a sliver of either surface"
+ assert pen[0].severity == Severity.WARN and r.passed
+ assert d["inside_count"] >= 4 and d["local_fraction"] >= 0.2 and 0.0 < d["through_ratio"] <= 2.0
+
+ # the same depth on a visible share of the part is still the ERROR it always was
+ post = trimesh.creation.box(extents=(0.2, 0.2, 0.2))
+ post.apply_translation((0, 0.45 + 0.1 - 0.017 - 0.018, 0)) # 17 mm of a fat post into the seat
+ r2 = check_connectivity(_scene(tmp_path / "post_seat.glb", Seat=seat, Post=post))
+ pen2 = _penetrations(r2)
+ assert pen2 and pen2[0].severity == Severity.ERROR and not r2.passed
+ assert pen2[0].data["fraction_inside"] >= PENETRATION_MIN_FRACTION
diff --git a/harness/tests/spatial_tools/test_contract.py b/harness/tests/spatial_tools/test_contract.py
index a357b3b4..13e46b8a 100644
--- a/harness/tests/spatial_tools/test_contract.py
+++ b/harness/tests/spatial_tools/test_contract.py
@@ -4,9 +4,9 @@ from pathlib import Path
import pytest
-from codeverse.contracts.artifacts import Measurement, PartMeasure, Severity
+from codeverse.contracts.artifacts import GateFinding, Measurement, PartMeasure, Severity
from codeverse.contracts.plan import BBox, CameraPlan, PartPlan, ScenePlan, StaticPlan, ZonePlan
-from codeverse.spatial.contract import check_contract, match_parts, plan_bbox_to_glb
+from codeverse.spatial.contract import check_contract, match_parts, plan_bbox_to_glb, planned_joins
from codeverse.spatial.measure import measure_glb
@@ -86,6 +86,36 @@ def test_match_parts_instances() -> None:
assert [e.name for e in extra] == ["Extra"]
+def test_planned_joins_pair_a_spanning_child_with_every_touching_parent_copy() -> None:
+ """An X-braced table: Brace runs Leg_1 → Leg_3 and its AABB also grazes Leg_0 at the
+ crossing, so three copies tie at gap 0. ``min`` on list order joined it to Leg_0 alone
+ and the gate printed "OPEN: Brace→Leg_0" for a brace that touches two legs; the gate
+ measures each candidate exactly and keeps the contact row per child, so the resolver
+ emits every tied copy and no guess. Leg_2 is clear of the box: not a candidate."""
+ 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:
"""Order must not decide it either: 'Slat1' is claimed by Slat1 even when the
Slat instances are matched first, and Slat still collects its real instances."""
@@ -162,3 +192,115 @@ def test_hints_are_written_in_the_authoring_frame() -> None:
leg = [f for f in check_contract(m, plan_tjs, language="threejs").findings if f.target == "Leg"][0]
assert "size 5.0×40.0×25.0 vs planned 5.0×40.0×5.0 cm (Δ x+0.0cm, y+0.0cm, z+20.0cm)" in leg.fix_hint
assert "(threejs frame: Y-up, +Z front)" in leg.fix_hint
+
+
+# --------------------------------------------------------------------------- orientation
+def _one_part_plan(extents_plan: tuple[float, float, float], *, up: int) -> StaticPlan:
+ """A plan whose single part IS the overall box, standing on the ground of a frame with
+ up axis ``up`` (2 for Z-up languages, 1 for Y-up)."""
+ c = [0.0, 0.0, 0.0]
+ c[up] = extents_plan[up] / 2
+ box = BBox(center=tuple(c), extents=extents_plan)
+ return StaticPlan(object_name="Thing", summary="s", overall_bbox=box,
+ parts=[PartPlan(name="Body", role="body", description="d", bbox=box)])
+
+
+def _measurement_glb(extents_glb: tuple[float, float, float]) -> Measurement:
+ """A GLB-frame (Y-up) measurement of one part ``Body`` standing on the ground."""
+ ex, ey, ez = extents_glb
+ lo, hi = (-ex / 2, 0.0, -ez / 2), (ex / 2, ey, ez / 2)
+ return Measurement(bbox_min=lo, bbox_max=hi, extents=extents_glb, center=(0.0, ey / 2, 0.0),
+ tri_count=12, n_meshes=1, n_islands=1, parts=[PartMeasure(name="Body", bbox_min=lo, bbox_max=hi)])
+
+
+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)
+ r = 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:
+ """Rotating the planned (0.4, 0.2, 1.2) box 90° about x swaps its y and z extents:
+ in Blender's frame it is now 0.2 m tall with the 1.2 m height running along y."""
+ 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.passed
+ assert o[0].data["best_axis"] == "y" and o[0].data["pose"] == "lying"
+ assert o[0].data["planned_up_m"] == pytest.approx(1.2) and o[0].data["measured_up_m"] == pytest.approx(0.2)
+ assert "lying down relative to the planned box: planned 120.0 cm tall (z), measured 20.0 cm tall" in o[0].message
+ assert "rotate the whole object 90° about x so its height runs along z (blender frame: Z-up, -Y front)" in o[0].fix_hint
+
+
+def test_the_same_in_the_threejs_frame() -> None:
+ # Y-up plan (0.4, 1.2, 0.2); built with the height along z: GLB (0.4, 0.2, 1.2)
+ r = check_contract(_measurement_glb((0.4, 0.2, 1.2)), _one_part_plan((0.4, 1.2, 0.2), up=1), language="threejs")
+ o = _orientation(r.findings)
+ assert len(o) == 1 and o[0].severity == Severity.ERROR and o[0].data["best_axis"] == "z"
+ assert "planned 120.0 cm tall (y)" in o[0].message and "about x so its height runs along y (threejs frame" in o[0].fix_hint
+
+
+def test_a_yaw_of_90_is_a_turned_warning() -> None:
+ # Blender plan (0.4, 0.2, 1.2) turned about z: plan-frame (0.2, 0.4, 1.2) → GLB (0.2, 1.2, 0.4)
+ r = check_contract(_measurement_glb((0.2, 1.2, 0.4)), _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.WARN and o[0].data["pose"] == "turned"
+ assert "turned 90° about z" in o[0].message and o[0].data["best_axis"] == "x"
+
+
+def test_a_near_cube_says_nothing_however_it_is_permuted() -> None:
+ plan = _one_part_plan((0.5, 0.45, 0.55), up=2)
+ for ext in ((0.55, 0.5, 0.45), (0.45, 0.55, 0.5), (0.5, 0.45, 0.55)):
+ assert not _orientation(check_contract(_measurement_glb(ext), plan, language="blender").findings), ext
+
+
+def test_a_sizing_error_is_a_contract_violation_not_an_orientation() -> None:
+ """Planner box 2× too big all round, and a build only half as tall: both deviate
+ (ERROR on the bbox) but nothing is sideways, so no orientation finding."""
+ plan = _one_part_plan((0.4, 0.2, 1.2), up=2)
+ for ext in ((0.2, 0.6, 0.1), (0.4, 0.6, 0.2)):
+ r = check_contract(_measurement_glb(ext), plan, language="blender")
+ assert not r.passed and any("bbox deviates" in f.message for f in r.errors)
+ assert not _orientation(r.findings), ext
+ # a cabinet planned 1.0 wide × 1.5 tall built 1.4 wide × 1.2 tall: its width is within
+ # 7% of the planned height, but 1.25× shorter is a proportion error, not a rotation
+ r = check_contract(_measurement_glb((1.4, 1.2, 0.5)), _one_part_plan((1.0, 0.5, 1.5), up=2), language="blender")
+ assert not r.passed and not _orientation(r.findings)
+
+
+def test_stood_on_end_needs_a_2x_change_in_height() -> None:
+ """Planners under-size tall objects: loop_w7 orrery_tj_ss r02 (threejs) was planned
+ 0.48×0.32×0.48 m and built 0.374×0.468×0.351 m, upright by eye — its height matches
+ the planned width within 3% and it is 1.46× taller than planned, which must NOT read
+ as 'stood on end'. A bench planned 1.5 m wide × 0.45 m tall that measures 0.45 wide
+ × 1.5 m tall is."""
+ orrery = _one_part_plan((0.48, 0.32, 0.48), up=1)
+ assert not _orientation(check_contract(_measurement_glb((0.374, 0.468, 0.351)), orrery, language="threejs").findings)
+ bench = _one_part_plan((1.5, 0.5, 0.45), up=2)
+ o = _orientation(check_contract(_measurement_glb((0.45, 1.5, 0.5)), bench, language="blender").findings)
+ assert len(o) == 1 and o[0].severity == Severity.ERROR and o[0].data["pose"] == "stood" and o[0].data["best_axis"] == "x"
+
+
+def test_the_turning_axis_must_keep_its_extent() -> None:
+ """sysprompt_ab_blender36 b36_v0_01r r01: a 'dining chair' planned 0.48×0.52×0.81 m
+ came out as a 1.38×0.68×0.46 m table. Its height shrank 1.8× and 0.68 m along y is
+ within 16% of the planned 0.81 m height — but a turn about x cannot change the x
+ extent, and x grew 2.9×: wrong object, not a rotated one."""
+ r = check_contract(_measurement_glb((1.38, 0.458, 0.68)), _one_part_plan((0.48, 0.52, 0.81), up=2), language="blender")
+ assert not r.passed and not _orientation(r.findings)
+
+
+def test_the_brilliana_c_clamp_is_caught_with_the_real_planner_box() -> None:
+ """h2h_brilliana_v1: the planner's box for 'a C-clamp with a threaded screw and swivel
+ pad' (cadquery, 12.5×9.6×22 cm) against the gallery GLB's measured extents
+ (astra3d-brilliana/gallery/c-clamp-mv, GLB 13.7×2.4×18.3 cm) — a clamp lying flat,
+ which the in-run judge missed and the visual re-judge caught. Note the planner's
+ 9.6 cm for a 2.4 cm thin axis: only the long axis can be required to reappear."""
+ plan = _one_part_plan((0.125, 0.096, 0.22), up=2)
+ r = check_contract(_measurement_glb((0.137, 0.024, 0.183)), plan, language="cadquery")
+ o = _orientation(r.findings)
+ assert len(o) == 1 and o[0].severity == Severity.ERROR and o[0].data["best_axis"] == "y"
+ assert o[0].data["measured_up_m"] == pytest.approx(0.024)
diff --git a/harness/tests/spatial_tools/test_measure.py b/harness/tests/spatial_tools/test_measure.py
index 17d57191..4085781e 100644
--- a/harness/tests/spatial_tools/test_measure.py
+++ b/harness/tests/spatial_tools/test_measure.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from pathlib import Path
+import numpy as np
import pytest
import trimesh
@@ -121,3 +122,74 @@ def test_instance_groups_bare_base_beside_indexed_siblings() -> None:
g = instance_groups(["lens", "lens_2", "lens_1", "tripod"])
assert g["lens"] == ["lens", "lens_1", "lens_2"]
assert g["tripod"] == ["tripod"]
+
+
+# ------------------------------------------------- 2026-08-30: world transforms and node names
+def _root_pivot_scene(dup_names: bool = False) -> trimesh.Scene:
+ """Two 0.1 x 0.1 x 0.4 posts authored Z-up under a root 'pivot' carrying the Z-up→Y-up
+ rotation — what THREE.GLTFExporter writes for a Z-up scene."""
+ rot = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]], float)
+ sc = trimesh.Scene()
+ sc.graph.update(frame_from=sc.graph.base_frame, frame_to="pivot", matrix=rot)
+ for i, x in enumerate((0.0, 0.3)):
+ box = trimesh.creation.box(extents=(0.1, 0.1, 0.4))
+ place = np.eye(4)
+ place[:3, 3] = (x, 0, 0.2) # on the NODE, so the walk has an edge to compose
+ sc.add_geometry(box, node_name=f"Post_{i}", geom_name=f"G{i}", parent_node_name="pivot", transform=place)
+ return sc
+
+
+def test_world_transform_composes_every_edge_up_to_the_root() -> None:
+ """``scene.graph.get`` left a scene-root matrix out of its descendants' world frames on
+ the brilliana desk lamp (an upright lamp measured lying down, 2026-08-30); the edge
+ walk is what the render rig agrees with. Here: the rotation on world→pivot must reach
+ a grandchild, composed in the right order."""
+ from codeverse.spatial.measure import world_transform
+
+ sc = _root_pivot_scene()
+ t = world_transform(sc, "Post_1")
+ # Post_1 sits at x=0.3, z=0.2 in the Z-up frame → world x=0.3, y=0.2
+ assert np.allclose(t[:3, 3], (0.3, 0.2, 0.0), atol=1e-9)
+ assert np.allclose(t[:3, :3], [[1, 0, 0], [0, 0, 1], [0, -1, 0]], atol=1e-9)
+ assert np.allclose(world_transform(sc, sc.graph.base_frame), np.eye(4))
+
+
+def test_a_root_pivot_glb_measures_upright(tmp_path: Path) -> None:
+ p = tmp_path / "pivot.glb"
+ p.write_bytes(_root_pivot_scene().export(file_type="glb"))
+ m = measure_glb(p)
+ assert m.bbox_min[1] == pytest.approx(0.0, abs=1e-6) and m.bbox_max[1] == pytest.approx(0.4, abs=1e-6)
+ assert m.ground_gap_m == pytest.approx(0.0, abs=1e-6)
+ assert not [f for f in m.extra.get("findings", []) if "node" in f]
+
+
+def test_duplicate_or_unnamed_glTF_nodes_are_named_in_the_findings(tmp_path: Path) -> None:
+ """The harness's own exporters name every node uniquely; a foreign THREE export with
+ 'Arm' x2 and 21 unnamed nodes mis-posed under trimesh — the reader must be told the
+ numbers are approximate rather than trust them (desk-lamp-q2, 2026-08-30)."""
+ import json
+ import struct
+
+ from codeverse.spatial.measure import gltf_node_names, node_name_findings
+
+ raw = _root_pivot_scene().export(file_type="glb")
+ (n,) = struct.unpack("<I", raw[12:16])
+ js = json.loads(raw[20:20 + n])
+ for node in js["nodes"]:
+ if node.get("name", "").startswith("Post_"):
+ node["name"] = "Post" # a duplicate
+ js["nodes"][0].pop("name", None) # and an unnamed one
+ body = json.dumps(js, separators=(",", ":")).encode()
+ body += b" " * ((4 - len(body) % 4) % 4)
+ glb = struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(body) + len(raw[20 + n:])) + struct.pack("<I", len(body)) + b"JSON" + body + raw[20 + n:]
+ p = tmp_path / "dups.glb"
+ p.write_bytes(glb)
+
+ assert gltf_node_names(p).count("Post") == 2
+ found = node_name_findings(p)
+ assert any("duplicate glTF node names ('Post' x2)" in f for f in found)
+ assert any(f"1 of {len(gltf_node_names(p))} glTF nodes are unnamed" in f for f in found)
+ assert found == [f for f in measure_glb(p).extra["findings"] if "glTF node" in f]
+ clean = tmp_path / "clean.glb"
+ clean.write_bytes(raw)
+ assert node_name_findings(clean) == []
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
index 6b07f9c8..81ea2119 100644
--- a/harness/tests/spatial_tools/test_tools.py
+++ b/harness/tests/spatial_tools/test_tools.py
@@ -395,6 +395,24 @@ def _stool_plan_with_missing_backrest() -> StaticPlan:
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 plan says ``Leg`` attaches to ``Seat``; the GLB has ``Leg_0..3``. The tool used to
+ hand the gate the raw plan names, so the agent-facing ledger listed ``Leg`` under
+ planned_unresolved while the track's gate resolved it (965 of 2 666 raw names over 357
+ stored rounds, 2026-08-30). One resolver now: ``spatial.contract.planned_joins``."""
+ 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
+
+
def test_build_folds_connectivity_and_contract_in_when_fewer_turns(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
"""docs/COST.md §29: ~25 check_connectivity + ~19 check_contract calls per run, each a 4 s
round trip for a < 0.5 s check. With the switch on, one build observation carries both."""