Official Codebase of 3DCodeVerse
Python
planner: plan-time geometry checks for articulated plans; joint-sweep findings aggregated per link pair (D44, D45)
ziyao72cd4a71c8dd
diff --git a/harness/codeverse/prompts/tracks/plan_articulated.j2 b/harness/codeverse/prompts/tracks/plan_articulated.j2index 823b5025..00decd4f 100644--- a/harness/codeverse/prompts/tracks/plan_articulated.j2+++ b/harness/codeverse/prompts/tracks/plan_articulated.j2@@ -37,6 +37,9 @@ WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):* `lower`/`upper` realistic limits (door 0..1.57 rad, lid 0..1.9 rad, drawer 0..0.8 × depth m);`rest` within the limits (usually 0 = closed).* `motion` one line: "lid opens upward about its back edge".+ * Count the moving parts the brief names (doors, drawers, lids, arms, wheels): that is the number of+ non-fixed joints, give or take one. Do not add joints to reach a part count — a rigid feature is a+ sub-part, not a link.* `parent` / `child` name top-level `parts` (links) — NEVER a sub-part: anything a joint moves must beits own link (the harness promotes a referenced sub-part to a link, but plan it as a link yourself).A `revolute` range stays within 2π; a part that turns freely (swivel, wheel) is `continuous`.diff --git a/harness/codeverse/spatial/joints.py b/harness/codeverse/spatial/joints.pyindex 908adea7..bbf1c5a0 100644--- a/harness/codeverse/spatial/joints.py+++ b/harness/codeverse/spatial/joints.py@@ -37,6 +37,7 @@ from codeverse.spatial.joints_sweep import (Overlap,SweepReport,SweepSummary,+ aggregate_findings,motion_direction_check,summary_text,sweep_collisions,@@ -47,5 +48,5 @@ __all__ = ["ARTICULATION_SHEET_NAME", "ZUP_TO_YUP", "Joint", "Link", "MotionCheck", "Overlap", "Robot", "SweepReport","SweepSummary", "UrdfError", "blender_render_glb", "fk", "joint_sweep_observation", "limit_poses","link_world_meshes", "load_urdf", "motion_direction_check", "pose_label", "pose_samples", "render_poses",- "robot_scene", "summary_text", "sweep_collisions", "sweep_findings", "urdf_to_glb", "world_bboxes",+ "robot_scene", "summary_text", "sweep_collisions", "aggregate_findings", "sweep_findings", "urdf_to_glb", "world_bboxes",]diff --git a/harness/codeverse/spatial/joints_sweep.py b/harness/codeverse/spatial/joints_sweep.pyindex 87890ef6..70d3d321 100644--- a/harness/codeverse/spatial/joints_sweep.py+++ b/harness/codeverse/spatial/joints_sweep.py@@ -238,6 +238,57 @@ def sweep_findings(report: SweepReport, *, rest_max_m: float = 0.005, hinge_cleareturn out+#: ERROR findings kept after aggregation (the deepest pairs); the rest fold into one WARN+MAX_PAIR_FINDINGS = 8+++def aggregate_findings(findings: list[GateFinding]) -> list[GateFinding]:+ """One finding per link pair (or per floating link), the worst pose first.++ compare_art_v3 (2026-08-28): a run produced 59 penetration findings for a handful of+ pairs — one per sampled pose — and the refine prompt carried them as 59 lines the+ agent could not act on; the loop burnt its budget without converging. Merge the+ poses of a pair into one line that says how many poses, the worst depth and where,+ keep the deepest ``MAX_PAIR_FINDINGS`` as ERRORs and summarise the remainder.+ """+ groups: dict[tuple[str, str | None], list[GateFinding]] = {}+ order: list[tuple[str, str | None]] = []+ for f in findings:+ key = (f.data.get("kind", ""), f.target)+ if key not in groups:+ groups[key] = []+ order.append(key)+ groups[key].append(f)+ merged: list[GateFinding] = []+ for key in order:+ fs = groups[key]+ if len(fs) == 1 or key[0] != "penetration":+ merged.extend(fs if key[0] != "penetration" else [fs[0]])+ continue+ worst = max(fs, key=lambda f: float(f.data.get("depth_m") or 0.0))+ rest = [f for f in fs if not f.data.get("pose")]+ moved = [f for f in fs if f.data.get("pose")]+ sev = Severity.ERROR if any(f.severity == Severity.ERROR for f in fs) else Severity.WARN+ worst_pose = worst.data.get("pose") or {}+ where = "at rest" if not worst_pose else "at " + ", ".join(f"{k}={v:.2f}" for k, v in worst_pose.items())+ msg = (f"links '{key[1]}' overlap in {len(fs)} of the sampled poses (worst {float(worst.data.get('depth_m') or 0) * 1000:.1f} mm "+ f"{where}" + (f"; {len(rest)} at rest" if rest and moved else "") + ")")+ merged.append(GateFinding(gate=worst.gate, severity=sev, target=worst.target, message=msg, fix_hint=worst.fix_hint,+ data={**worst.data, "n_poses": len(fs), "poses": [f.data.get("pose") for f in fs][:12],+ "max_depth_m": float(worst.data.get("depth_m") or 0.0)}))+ errors = sorted([f for f in merged if f.severity == Severity.ERROR],+ key=lambda f: -float(f.data.get("max_depth_m") or f.data.get("depth_m") or f.data.get("gap_m") or 0.0))+ warns = [f for f in merged if f.severity != Severity.ERROR]+ if len(errors) > MAX_PAIR_FINDINGS:+ extra = errors[MAX_PAIR_FINDINGS:]+ errors = errors[:MAX_PAIR_FINDINGS]+ warns.append(GateFinding(gate=extra[0].gate, severity=Severity.WARN, target="overall",+ message=f"{len(extra)} more overlapping pair(s) not listed: " + ", ".join(str(f.target) for f in extra[:10]),+ fix_hint="fix the listed pairs first; the rest are re-measured after the next build",+ data={"kind": "penetration_summary", "pairs": [f.target for f in extra]}))+ return errors + warns++# ------------------------------------------------------------------ motion direction_DIRS: dict[str, tuple[float, float, float]] = {"+x": (1, 0, 0), "-x": (-1, 0, 0), "+y": (0, 1, 0), "-y": (0, -1, 0), "+z": (0, 0, 1), "-z": (0, 0, -1),diff --git a/harness/codeverse/tracks/articulated_object.py b/harness/codeverse/tracks/articulated_object.pyindex e7f4f88f..f31906af 100644--- a/harness/codeverse/tracks/articulated_object.py+++ b/harness/codeverse/tracks/articulated_object.py@@ -123,7 +123,8 @@ def default_joint_sweep(ws: Workspace, plan: Plan | None, out_dir: Path) -> tuplreturn GateReport(gate=SWEEP_GATE, passed=False, findings=[GateFinding(gate=SWEEP_GATE, severity=Severity.ERROR, target="robot.urdf", message=f"URDF sweep failed: {e}",fix_hint="fix robot.urdf so every link has a mesh under meshes/<link>.glb and joints form one tree")]), []- findings = [f.model_copy(update={"gate": SWEEP_GATE}) for f in joints.sweep_findings(report)]+ findings = [f.model_copy(update={"gate": SWEEP_GATE})+ for f in joints.aggregate_findings(joints.sweep_findings(report))]gate = GateReport(gate=SWEEP_GATE, passed=not any(f.severity == Severity.ERROR for f in findings), findings=findings,duration_ms=int((time.time() - t0) * 1000))views: list[RenderView] = []diff --git a/harness/codeverse/tracks/plan_checks.py b/harness/codeverse/tracks/plan_checks.pynew file mode 100644index 00000000..9b9200ac--- /dev/null+++ b/harness/codeverse/tracks/plan_checks.py@@ -0,0 +1,230 @@+"""Plan-time geometry checks for articulated plans (2026-08-28).++The planner's boxes, pivots and axes are enough to catch the three mistakes that cost+compare_art_v3 its low scores — a pivot nowhere near the part it turns, a child that does+not touch the link it attaches to, and a part that sweeps through a neighbour over its+joint range — BEFORE any code is written. Each mistake found here is a re-ask of the+planner (:data:`codeverse.tracks.planner.MAX_GEOMETRY_REASKS`), not a gate on a build+that already cost a round.++Everything is axis-aligned-box arithmetic on the plan's own numbers. The checks are+deliberately conservative: the moving part's own subtree and any link whose box CONTAINS+>= ``HOUSING_FRACTION`` of the moving part at rest (a cabinet around a drawer, a frame around a sash) are never+collision candidates, and only a real intersection (>= ``COLLISION_MIN_M`` on every axis,+or half the part's thickness for thin parts) counts.+A false complaint costs one re-ask; a missed one costs nothing that the joint sweep does+not still catch.+"""++from __future__ import annotations++import math+from dataclasses import dataclass+from typing import Any++from codeverse.conventions import to_snake++#: a hinge line must lie within this margin of BOTH the child's and the parent's box+PIVOT_TOL_M = 0.025+#: a child's box must come within this gap of its parent's box (touching = 0)+ATTACH_GAP_M = 0.015+#: a swept box must overlap a neighbour by at least this on EVERY axis to count as a collision+COLLISION_MIN_M = 0.02+#: a link whose box holds at least this share of the moving part at rest is its housing+#: (cabinet around a drawer, frame around a sash) and is never a collision candidate+HOUSING_FRACTION = 0.8+#: points sampled per box axis when posing a part (5³ = 125 points; a point, unlike the+#: axis-aligned box of a rotated part, is never an over-approximation)+SAMPLES_PER_AXIS = 5+#: at most this many complaints per re-ask (the worst first)+MAX_COMPLAINTS = 6++Vec = tuple[float, float, float]+++@dataclass(frozen=True)+class Box:+ lo: Vec+ hi: Vec++ @classmethod+ def from_bbox(cls, bbox: Any) -> Box:+ c, e = bbox.center, bbox.extents+ return cls(tuple(c[i] - e[i] / 2 for i in range(3)), tuple(c[i] + e[i] / 2 for i in range(3))) # type: ignore[arg-type]++ @classmethod+ def of_points(cls, pts: list[Vec]) -> Box:+ return cls(tuple(min(p[i] for p in pts) for i in range(3)), tuple(max(p[i] for p in pts) for i in range(3))) # type: ignore[arg-type]++ def corners(self) -> list[Vec]:+ return [(x, y, z) for x in (self.lo[0], self.hi[0]) for y in (self.lo[1], self.hi[1]) for z in (self.lo[2], self.hi[2])]++ def samples(self, n: int = SAMPLES_PER_AXIS) -> list[Vec]:+ """An n×n×n lattice over the box (corners, edges, faces and interior)."""+ axes = [[self.lo[i] + (self.hi[i] - self.lo[i]) * k / (n - 1) for k in range(n)] for i in range(3)]+ return [(x, y, z) for x in axes[0] for y in axes[1] for z in axes[2]]++ def depth_of_point(self, p: Vec) -> float:+ """How far inside the box ``p`` lies (distance to the nearest face); <= 0 outside."""+ return min(min(p[i] - self.lo[i], self.hi[i] - p[i]) for i in range(3))++ def center(self) -> Vec:+ return tuple((self.lo[i] + self.hi[i]) / 2 for i in range(3)) # type: ignore[return-value]++ def gap_to(self, other: Box) -> float:+ """Largest per-axis separation (0 when the boxes touch or overlap)."""+ return max(0.0, *[max(self.lo[i] - other.hi[i], other.lo[i] - self.hi[i]) for i in range(3)])++ def dist_to_point(self, p: Vec) -> float:+ return math.sqrt(sum(max(self.lo[i] - p[i], 0.0, p[i] - self.hi[i]) ** 2 for i in range(3)))++ def overlap_depth(self, other: Box) -> float:+ """Smallest per-axis overlap (a true intersection depth); <= 0 when they do not intersect."""+ return min(min(self.hi[i], other.hi[i]) - max(self.lo[i], other.lo[i]) for i in range(3))++ def contains(self, other: Box, slack: float = 0.0) -> bool:+ return all(self.lo[i] - slack <= other.lo[i] and other.hi[i] <= self.hi[i] + slack for i in range(3))++ def volume(self) -> float:+ return math.prod(max(self.hi[i] - self.lo[i], 0.0) for i in range(3))++ def fraction_inside(self, other: Box) -> float:+ """Share of this box's volume that lies inside ``other`` (1 = fully housed).+ A degenerate (zero-volume) box falls back to containment with ``PIVOT_TOL_M`` slack."""+ v = self.volume()+ if v <= 0.0:+ return 1.0 if other.contains(self, slack=PIVOT_TOL_M) else 0.0+ inter = math.prod(max(min(self.hi[i], other.hi[i]) - max(self.lo[i], other.lo[i]), 0.0) for i in range(3))+ return inter / v+++def _rotate(p: Vec, axis: Vec, pivot: Vec, angle: float) -> Vec:+ """Rodrigues rotation of ``p`` about the unit ``axis`` through ``pivot``."""+ ax, ay, az = axis+ n = math.sqrt(ax * ax + ay * ay + az * az) or 1.0+ ax, ay, az = ax / n, ay / n, az / n+ vx, vy, vz = p[0] - pivot[0], p[1] - pivot[1], p[2] - pivot[2]+ c, s = math.cos(angle), math.sin(angle)+ dot = ax * vx + ay * vy + az * vz+ cx, cy, cz = ay * vz - az * vy, az * vx - ax * vz, ax * vy - ay * vx+ rx = vx * c + cx * s + ax * dot * (1 - c)+ ry = vy * c + cy * s + ay * dot * (1 - c)+ rz = vz * c + cz * s + az * dot * (1 - c)+ return (pivot[0] + rx, pivot[1] + ry, pivot[2] + rz)+++def _posed_points(box: Box, joint: Any, q: float) -> list[Vec]:+ pts = box.samples()+ if joint.type in ("revolute", "continuous"):+ return [_rotate(c, tuple(joint.axis), tuple(joint.pivot), q) for c in pts]+ if joint.type == "prismatic":+ ax = tuple(joint.axis)+ n = math.sqrt(sum(a * a for a in ax)) or 1.0+ d = tuple(a / n * q for a in ax)+ return [(p[0] + d[0], p[1] + d[1], p[2] + d[2]) for p in pts]+ return pts+++def _spins_in_place(box: Box, joint: Any) -> bool:+ """True when the joint axis passes through the part's core (a wheel on its axle, a lead+ screw, a mirror in a yoke): the part turns where it is and sweeps nothing new."""+ ax = tuple(joint.axis)+ n = math.sqrt(sum(a * a for a in ax)) or 1.0+ ax = (ax[0] / n, ax[1] / n, ax[2] / n)+ c, pv = box.center(), tuple(joint.pivot)+ v = (c[0] - pv[0], c[1] - pv[1], c[2] - pv[2])+ t = sum(v[i] * ax[i] for i in range(3))+ off = math.sqrt(max(sum((v[i] - t * ax[i]) ** 2 for i in range(3)), 0.0))+ return off <= 0.5 * min(box.hi[i] - box.lo[i] for i in range(3))+++def _ancestors(link: str, parent_of: dict[str, str]) -> set[str]:+ out: set[str] = set()+ cur = parent_of.get(link)+ while cur is not None and cur not in out:+ out.add(cur)+ cur = parent_of.get(cur)+ return out+++def geometry_complaints(plan: Any) -> list[str]:+ """Numbered, specific complaints about an :class:`ArticulatedPlan`'s geometry ([] = fine)."""+ parts = {to_snake(p.name): p for p in getattr(plan, "parts", [])}+ joints = list(getattr(plan, "joints", []) or [])+ if not parts or not joints:+ return []+ boxes = {k: Box.from_bbox(p.bbox) for k, p in parts.items()}+ parent_of = {to_snake(j.child): to_snake(j.parent) for j in joints}+ out: list[tuple[float, str]] = [] # (severity score, text)++ for j in joints:+ c, p = to_snake(j.child), to_snake(j.parent)+ if c not in boxes or p not in boxes:+ continue+ cb, pb = boxes[c], boxes[p]+ # A. attachment: the child's box must reach its parent's box+ gap = cb.gap_to(pb)+ if gap > ATTACH_GAP_M:+ out.append((gap, f"joint {j.name}: link {j.child} is {gap * 1000:.0f} mm away from its parent {j.parent} "+ f"(boxes do not touch) — move or enlarge {j.child} so it meets {j.parent}, or attach it "+ f"to the link it really sits on"))+ if j.type == "fixed":+ continue+ # B. hinge placement: the pivot of a revolute / continuous joint lies where the two+ # links meet. (A prismatic pivot is only the child frame's origin — anywhere on+ # the rail is legal — so it is not checked.)+ pv = tuple(j.pivot)+ if j.type in ("revolute", "continuous"):+ dc, dp = cb.dist_to_point(pv), pb.dist_to_point(pv)+ if dc > PIVOT_TOL_M or dp > PIVOT_TOL_M:+ far = j.child if dc > dp else j.parent+ out.append((max(dc, dp), f"joint {j.name}: pivot {[round(x, 3) for x in pv]} is {max(dc, dp) * 1000:.0f} mm "+ f"from {far}'s box (hinge lines sit where the two links meet) — "+ f"put the pivot on the shared edge of {j.parent} and {j.child}"))+ if _spins_in_place(cb, j):+ continue # turns where it is: nothing to sweep+ # C. swept collision. The child's box is posed at q=lower/upper as a point lattice+ # and tested against every link that is neither carried by the child (its+ # subtree), a housing round it (>= HOUSING_FRACTION of it at rest), interlocked+ # with it at rest (they already intersect — crossing scissor arms, folded ribs,+ # a screw through a jaw: the joint sweep measures the real meshes later), nor —+ # for a slide — the parent it runs in/on. The parent of a hinge IS a candidate+ # when it does not house the child: a door must not swing through its cabinet.+ # Thin parts count at half their thickness.+ qs = [j.lower, j.upper] if j.type in ("revolute", "prismatic") else [math.pi / 2, math.pi]+ exclude = {c} | {k for k in boxes if c in _ancestors(k, parent_of)}+ if j.type == "prismatic":+ exclude.add(p)+ min_depth = min(COLLISION_MIN_M, 0.5 * min(cb.hi[i] - cb.lo[i] for i in range(3)))+ for other, ob in boxes.items():+ if other in exclude or cb.fraction_inside(ob) >= HOUSING_FRACTION or cb.overlap_depth(ob) >= min_depth:+ continue+ worst_q, worst_depth = None, 0.0+ for q in qs:+ if abs(q) < 1e-9:+ continue+ depth = max(ob.depth_of_point(pt) for pt in _posed_points(cb, j, q))+ if depth > worst_depth:+ worst_q, worst_depth = q, depth+ if worst_q is not None and worst_depth >= min_depth:+ unit = "rad" if j.type != "prismatic" else "m"+ out.append((worst_depth, f"joint {j.name}: at q={worst_q:.2f} {unit} link {j.child} sweeps "+ f"{worst_depth * 1000:.0f} mm deep into {parts[other].name} — shorten "+ f"{j.child} on that side, move the pivot, or reduce the range "+ f"[{j.lower}, {j.upper}] so the motion clears {parts[other].name}"))+ out.sort(key=lambda t: -t[0])+ return [t for _, t in out[:MAX_COMPLAINTS]]+++def plan_geometry_complaint(plan: Any) -> str:+ """"" when the plan's geometry is consistent; otherwise the re-ask text."""+ items = geometry_complaints(plan)+ if not items:+ return ""+ return ("Your plan is valid but its geometry contradicts itself. Fix EXACTLY these problems (move boxes, pivots "+ "or ranges; keep every part and joint) and return the full corrected plan JSON again (same schema):\n- "+ + "\n- ".join(items))+++__all__ = ["ATTACH_GAP_M", "COLLISION_MIN_M", "HOUSING_FRACTION", "MAX_COMPLAINTS", "PIVOT_TOL_M", "SAMPLES_PER_AXIS", "Box", "geometry_complaints",+ "plan_geometry_complaint"]diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.pyindex 40964ab5..d8919483 100644--- a/harness/codeverse/tracks/plan_features.py+++ b/harness/codeverse/tracks/plan_features.py@@ -62,6 +62,9 @@ def pin_plan_blockers(variant_env: dict[str, str]) -> list[str]:#: honest by tests/orchestrator_tracks/test_plan_features.py, which greps the tree.LIVE_SWITCHES: dict[str, str] = {"CV3D_PLAN_BRIEF": "codeverse/tracks/planner.py", # brief.py merged in, 2026-08-28+ # plan-time geometry re-ask for articulated plans (tracks/plan_checks.py); plan-side,+ # so an A/B over it can never --pin-plan+ "CV3D_PLAN_GEOMETRY": "codeverse/tracks/planner.py","CV3D_SCOPED_PARTS": "codeverse/tracks/depth.py","CV3D_DETAIL_ROUNDS": "codeverse/tracks/lifecycle.py","CV3D_REFERENCE_DIFF": "codeverse/judges/vlm_judge.py", # reference.py merged in, 2026-08-28diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.pyindex 7dce7d2a..3df7282e 100644--- a/harness/codeverse/tracks/planner.py+++ b/harness/codeverse/tracks/planner.py@@ -574,6 +574,16 @@ P = TypeVar("P", bound=BaseModel)#: different failures and get separate chances (see ``plan_with_usage``).MAX_VALIDATION_REASKS = 2 # was 1: compare_art_v2 lost 5 of 14 articulated prompts at this gate (2026-08-25)MAX_QUALITY_REASKS = 1+#: a plan whose boxes / pivots / ranges contradict each other (tracks/plan_checks.py) is+#: re-asked with the numbers; after this many it ships anyway and the joint sweep decides+MAX_GEOMETRY_REASKS = 2+#: ``CV3D_PLAN_GEOMETRY=0`` turns the geometry re-ask off (a control arm for an A/B;+#: registered in tracks/plan_features.LIVE_SWITCHES)+PLAN_GEOMETRY_ENV = "CV3D_PLAN_GEOMETRY"+++def geometry_check_enabled() -> bool:+ return os.environ.get(PLAN_GEOMETRY_ENV, "1").strip().lower() not in ("0", "false", "off", "no")#: Output room for the plan call, sized from the plan budget. A deep plan is much longer#: JSON than a flat one AND Gemini 3.x bills its thinking against the same ceiling, so the#: flat 24 000 that served 8 box-parts truncates a 12-part plan with sub-parts —@@ -721,7 +731,8 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]last_error = ""invalid = requeried = grown = 0tokens = plan_tokens(budget, max_output_tokens)- for attempt in range(2 + MAX_VALIDATION_REASKS + MAX_QUALITY_REASKS):+ geo_reasked = 0+ for attempt in range(2 + MAX_VALIDATION_REASKS + MAX_QUALITY_REASKS + MAX_GEOMETRY_REASKS):req = ChatRequest(messages=messages, system=system, response_schema=schema, temperature=temperature,thinking="medium", max_output_tokens=tokens, label=f"planner{'-retry' if attempt else ''}",max_wait_s=plan_wait_s(tokens, guard))@@ -766,6 +777,16 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]target_parts=budget.target_parts, complaint=complaint[:400])messages = messages + [_echo(raw, resp.text), ChatMessage.user(complaint)]continue+ if geo_reasked < MAX_GEOMETRY_REASKS and getattr(result, "joints", None) and geometry_check_enabled():+ from codeverse.tracks.plan_checks import plan_geometry_complaint++ geo = plan_geometry_complaint(result)+ if geo:+ geo_reasked += 1+ if events is not None:+ events.emit("plan.geometry", attempt=attempt, reask=geo_reasked, complaint=geo[:600])+ messages = messages + [_echo(raw, resp.text), ChatMessage.user(geo)]+ continuenormalised = list(getattr(result, "normalisations", None) or [])if normalised and events is not None:events.emit("plan.normalised", attempt=attempt, n=len(normalised), items=normalised[:8])@@ -900,6 +921,6 @@ def normalise_names[P: BaseModel](plan_obj: P) -> P:return plan_obj-__all__ = ["MAX_QUALITY_REASKS", "MAX_VALIDATION_REASKS", "PLAN_TOKENS_MAX", "PlanningError", "plan",+__all__ = ["MAX_GEOMETRY_REASKS", "PLAN_GEOMETRY_ENV", "geometry_check_enabled", "MAX_QUALITY_REASKS", "MAX_VALIDATION_REASKS", "PLAN_TOKENS_MAX", "PlanningError", "plan","plan_tokens", "plan_with_usage", "plan_example", "ensure_acceptance", "add_acceptance_item","default_event_stats", "normalise_names", "build_system_prompt", "build_user_prompt", "load_prompt_or"]diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex 1f63ec1f..ef5840e6 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -170,6 +170,9 @@ codeverse/can be A/B'd alone, + pin_plan_blockers() deciding when two arms may shareone plan — docs/PLAN_LOOP.md, docs/EVAL.md §8.1),depth.py,+ plan_checks.py (plan-time geometry checks on an ArticulatedPlan — attachment,+ pivot placement, swept-box collision over the joint range — fed back to the+ planner as a re-ask before any code is written),skills_hook.py (the round's view of codeverse/skills: attach before generating,probe reads after — a no-op unless CV3D_SKILLS is on)flywheel/ record.py, export.py, pack.py, sample.py, pairs.py, migrate.py (schema moves),diff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.mdindex 52d3b0f6..d90e7753 100644--- a/harness/docs/DECISIONS.md+++ b/harness/docs/DECISIONS.md@@ -234,6 +234,33 @@ written) that were accepted because the code works that way and the tests pin itin `build_once`. Decision: `_ast_lint.safe_parse` catches SyntaxError / RecursionError /SystemError / MemoryError / ValueError; every python lint reports a lint ERROR with aflatten-the-literal hint instead.+* **D44 An articulated plan is checked for geometric self-consistency before any code+ is written (2026-08-28).** Context: compare_art_v3's low scorers failed on kinematics+ the plan already contradicted — a pivot nowhere near the door it turns, a stretcher link+ floating 40 mm off its parent, a lid whose range swings it through the box — and the+ joint sweep only reported it after a full build round. Decision:+ `tracks/plan_checks.geometry_complaints` runs three box-arithmetic checks on the plan's+ own numbers (attachment gap ≤ 15 mm; pivot within 20 mm of BOTH links; the child's box+ posed at q=lower/upper against every link that is neither its subtree nor a housing+ holding ≥ 80 % of it at rest, real intersection ≥ 20 mm or half the part's thickness),+ and the planner re-asks with the numbers (`MAX_GEOMETRY_REASKS = 2`, event+ `plan.geometry`). After the cap the plan SHIPS — this never raises `PlanningError`+ (the plan-loop wave's C1 `fit` re-ask, docs/PLAN_LOOP.md §2, killed 3 of 8 cells that+ way and was reverted). Articulated plans only; `CV3D_PLAN_GEOMETRY=0` is the control+ arm (`plan_features.LIVE_SWITCHES`). Retro-fired on the 14 recorded compare_art_v3+ plans: 8 draw a complaint (mean score 0.362), 6 do not (0.610); the six lowest scorers+ all draw one. Its effect is read on judge-free quantities the+ 8–14-prompt batteries CAN resolve — joint_sweep error count, build rate, rounds to a+ clean sweep — not on the judge mean (docs/EVAL.md §8.1).+* **D45 Joint-sweep findings reach the fixer aggregated per link pair (2026-08-28).**+ Context: one compare_art_v3 run produced 59 penetration findings for a handful of pairs+ — one line per sampled pose — and `build_refine_instructions` de-duplicates by+ (target, kind) keeping the FIRST pose's line, so the agent saw the shallowest instance+ and the loop burnt its budget without converging. Decision:+ `spatial/joints_sweep.aggregate_findings` merges a pair's poses into one line (how many+ poses, worst depth and at which q, rest count), ranks ERRORs by depth, keeps the+ deepest `MAX_PAIR_FINDINGS = 8` and folds the rest into one WARN+ `penetration_summary`; `default_joint_sweep` applies it. The raw report is unchanged.## Rejected / deferreddiff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.pyindex edc488f8..19dbf339 100644--- a/harness/tests/flywheel_cli/test_cli.py+++ b/harness/tests/flywheel_cli/test_cli.py@@ -23,7 +23,7 @@ def made_run(tmp_path: Path):runs = tmp_path / "runs"r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", *extra])assert r.exit_code == 0, r.output- return runs, next(d for d in runs.iterdir() if d.is_dir())+ return runs, next(d for d in runs.iterdir() if d.is_dir() and not d.name.startswith("."))return make@@ -242,7 +242,7 @@ def test_make_texture_flag_sets_spec_options(tmp_path: Path):runs = tmp_path / "runs"r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run", "--texture", "--candidates", "3"])assert r.exit_code == 0, r.output- ws = next(d for d in runs.iterdir() if d.is_dir())+ ws = next(d for d in runs.iterdir() if d.is_dir() and not d.name.startswith("."))spec = Spec.model_validate_json((ws / "spec.json").read_text())# run-shape options are frozen on the spec (no more magic 'texture' tag)assert spec.options.texture is True and spec.options.candidates == 3@@ -253,7 +253,7 @@ def test_make_language_defaults_to_the_tracks_first(tmp_path: Path):runs = tmp_path / "runs"r = runner.invoke(app, ["make", "a harbour at night", "--track", "scene", "--runs-dir", str(runs), "--no-run"])assert r.exit_code == 0, r.output- ws = next(d for d in runs.iterdir() if d.is_dir())+ ws = next(d for d in runs.iterdir() if d.is_dir() and not d.name.startswith("."))spec = Spec.model_validate_json((ws / "spec.json").read_text())assert spec.language.value == "scene_threejs"diff --git a/harness/tests/orchestrator_tracks/test_planner_geometry_reask.py b/harness/tests/orchestrator_tracks/test_planner_geometry_reask.pynew file mode 100644index 00000000..7283040d--- /dev/null+++ b/harness/tests/orchestrator_tracks/test_planner_geometry_reask.py@@ -0,0 +1,66 @@+"""The planner re-asks on a geometrically inconsistent articulated plan (tracks/plan_checks.py)."""++from __future__ import annotations++import copy++from codeverse.contracts.common import Language, Track+from codeverse.contracts.plan import ArticulatedPlan+from codeverse.proc import EventLog+from codeverse.tracks.planner import MAX_GEOMETRY_REASKS, plan, plan_example+from tests.orchestrator_tracks.conftest import make_spec+from tests.orchestrator_tracks.fakes import FakeChatModel, FakeRuntime+++def _good() -> dict:+ return copy.deepcopy(plan_example(Track.ARTICULATED_OBJECT))+++def _bad() -> dict:+ d = _good()+ j = d["joints"][0]+ j.update(type="revolute", pivot=[0.9, -0.02, 0.45], lower=0.0, upper=1.0) # a hinge 700 mm outside the cabinet+ return d+++def _spec():+ return make_spec(track=Track.ARTICULATED_OBJECT, language=Language.URDF_BLENDER, prompt="a desk drawer unit")+++def test_geometry_complaint_reasks_then_accepts(tmp_ws):+ answers = [_bad(), _good()]+ model = FakeChatModel(lambda req: answers.pop(0))+ events = EventLog(tmp_ws.events_path)+ p = plan(_spec(), "fake:planner", ArticulatedPlan, tmp_ws, model=model, events=events,+ runtime=FakeRuntime(Language.URDF_BLENDER))+ assert isinstance(p, ArticulatedPlan) and len(model.requests) == 2+ reask = model.requests[1].messages[-1].text+ assert "geometry contradicts itself" in reask and "DrawerSlide" in reask and "pivot" in reask+ kinds = [e["event"] for e in events.read()]+ assert "plan.geometry" in kinds and "plan.done" in kinds+++def test_geometry_reasks_are_capped_and_the_plan_ships(tmp_ws):+ model = FakeChatModel(lambda req: _bad())+ p = plan(_spec(), "fake:planner", ArticulatedPlan, tmp_ws, model=model, runtime=FakeRuntime(Language.URDF_BLENDER))+ assert isinstance(p, ArticulatedPlan)+ assert len(model.requests) == 1 + MAX_GEOMETRY_REASKS == 3+ assert all("geometry contradicts" in r.messages[-1].text for r in model.requests[1:])+++def test_static_plans_skip_the_geometry_check(tmp_ws):+ from codeverse.contracts.plan import StaticPlan+ from tests.orchestrator_tracks.test_generation_planner_repair import _valid_plan_dict++ model = FakeChatModel(lambda req: _valid_plan_dict())+ plan(make_spec(), "fake:planner", StaticPlan, tmp_ws, model=model, runtime=FakeRuntime(Language.THREEJS))+ assert len(model.requests) == 1+++def test_switch_off_skips_the_geometry_reask(tmp_ws, monkeypatch):+ from codeverse.tracks.planner import PLAN_GEOMETRY_ENV++ monkeypatch.setenv(PLAN_GEOMETRY_ENV, "0")+ model = FakeChatModel(lambda req: _bad())+ p = plan(_spec(), "fake:planner", ArticulatedPlan, tmp_ws, model=model, runtime=FakeRuntime(Language.URDF_BLENDER))+ assert isinstance(p, ArticulatedPlan) and len(model.requests) == 1diff --git a/harness/tests/plan_checks/__init__.py b/harness/tests/plan_checks/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/harness/tests/plan_checks/test_geometry.py b/harness/tests/plan_checks/test_geometry.pynew file mode 100644index 00000000..4d2b6d7a--- /dev/null+++ b/harness/tests/plan_checks/test_geometry.py@@ -0,0 +1,189 @@+"""Plan-time geometry checks (tracks/plan_checks.py) on synthetic articulated plans."""++import math++from codeverse.contracts.artifacts import GateFinding, Severity+from codeverse.contracts.common import Track+from codeverse.contracts.plan import ArticulatedPlan+from codeverse.spatial.joints_sweep import MAX_PAIR_FINDINGS, aggregate_findings+from codeverse.tracks.plan_checks import (+ ATTACH_GAP_M,+ COLLISION_MIN_M,+ HOUSING_FRACTION, # noqa: I001+ PIVOT_TOL_M,+ Box,+ geometry_complaints,+ plan_geometry_complaint,+)+from codeverse.tracks.planner import plan_example+++def _part(name, center, extents, attach_to=None, **kw):+ return {"name": name, "role": f"{name} of the cabinet", "description": f"{name} body",+ "bbox": {"center": list(center), "extents": list(extents)}, "attach_to": attach_to, "material": "wood", **kw}+++def _weld(name, parent, child):+ return {"name": name, "type": "fixed", "parent": parent, "child": child, "axis": [0, 0, 1],+ "pivot": [0, 0, 0], "lower": 0.0, "upper": 0.0, "rest": 0.0, "motion": "rigid"}+++def _cabinet_with_door(pivot=(-0.2, -0.25, 0.3), axis=(0, 0, 1), lower=-math.pi / 2, upper=0.0, extra=(), welds=()):+ parts = [+ _part("Cabinet", (0, 0, 0.3), (0.4, 0.5, 0.6)),+ # door hangs on the cabinet's front-left edge (x=-0.2, y=-0.25)+ _part("Door", (0, -0.26, 0.3), (0.4, 0.02, 0.6), attach_to="Cabinet"),+ *extra,+ ]+ return ArticulatedPlan.model_validate({+ "object_name": "SideCabinet", "summary": "a cabinet with one hinged door", "root_link": "Cabinet",+ "overall_bbox": {"center": [0, -0.05, 0.3], "extents": [0.6, 0.7, 0.6]}, "parts": parts,+ "joints": [{"name": "DoorHinge", "type": "revolute", "parent": "Cabinet", "child": "Door",+ "axis": list(axis), "pivot": list(pivot), "lower": lower, "upper": upper,+ "rest": 0.0, "motion": "the door swings open to the front-left"}, *welds],+ })+++def test_example_and_good_door_are_clean():+ assert geometry_complaints(ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))) == []+ assert plan_geometry_complaint(_cabinet_with_door()) == ""+++def test_pivot_far_from_both_links_is_a_complaint():+ plan = _cabinet_with_door(pivot=(0.5, -0.25, 0.3)) # 300 mm right of the cabinet+ items = geometry_complaints(plan)+ assert len(items) == 1 and "pivot" in items[0] and "DoorHinge" in items[0]+ assert "300 mm" in items[0]+++def _plan(parts, joints, root="Base"):+ return ArticulatedPlan.model_validate({+ "object_name": "Rig", "summary": "test rig", "root_link": root,+ "overall_bbox": {"center": [0, 0, 0.5], "extents": [1.5, 1.5, 1.5]}, "parts": parts, "joints": joints})+++def _joint(name, typ, parent, child, axis, pivot, lower, upper):+ return {"name": name, "type": typ, "parent": parent, "child": child, "axis": list(axis), "pivot": list(pivot),+ "lower": lower, "upper": upper, "rest": 0.0, "motion": "moves"}+++def test_telescoping_leg_and_spinning_wheel_are_not_collisions():+ # a lower leg sliding 400 mm up INTO its upper leg (prismatic: the parent is never a candidate)+ plan = _plan([_part("Base", (0, 0, 1.0), (0.1, 0.1, 0.1)),+ _part("UpperLeg", (0, 0, 0.7), (0.04, 0.04, 0.6), attach_to="Base"),+ _part("LowerLeg", (0, 0, 0.25), (0.03, 0.03, 0.5), attach_to="UpperLeg")],+ [_joint("UpperWeld", "fixed", "Base", "UpperLeg", (0, 0, 1), (0, 0, 0.95), 0, 0),+ _joint("LegSlide", "prismatic", "UpperLeg", "LowerLeg", (0, 0, 1), (0, 0, 0.5), 0.0, 0.4)])+ assert geometry_complaints(plan) == []+ # a wheel spinning on an axle through its centre, flanked by a fork it would "sweep" as a box+ plan = _plan([_part("Base", (0, 0, 0.3), (0.1, 0.1, 0.1)),+ _part("Fork", (0, 0, 0.15), (0.12, 0.02, 0.3), attach_to="Base"),+ _part("Wheel", (0, -0.03, 0.05), (0.1, 0.04, 0.1), attach_to="Fork")],+ [_joint("ForkWeld", "fixed", "Base", "Fork", (0, 0, 1), (0, 0, 0.25), 0, 0),+ _joint("Axle", "continuous", "Fork", "Wheel", (0, 1, 0), (0, -0.03, 0.05), 0, 0)])+ assert geometry_complaints(plan) == []+++def test_parts_interlocked_at_rest_are_left_to_the_joint_sweep():+ # two crossing scissor arms whose boxes already intersect at rest+ plan = _plan([_part("Base", (0, 0, 0.05), (0.3, 0.1, 0.1)),+ _part("ArmA", (0, 0, 0.3), (0.3, 0.02, 0.4), attach_to="Base"),+ _part("ArmB", (0, 0.01, 0.3), (0.3, 0.02, 0.4), attach_to="ArmA")],+ [_joint("ArmAHinge", "revolute", "Base", "ArmA", (0, 1, 0), (-0.15, 0, 0.1), -0.8, 0.8),+ _joint("Scissor", "revolute", "ArmA", "ArmB", (0, 1, 0), (0, 0, 0.3), -0.8, 0.8)])+ assert not any("sweeps" in i and "ArmB" in i and "ArmA" in i for i in geometry_complaints(plan))+++def _with_knob(y):+ return _cabinet_with_door(extra=[_part("Knob", (0, y, 0.3), (0.03, 0.03, 0.03), attach_to="Door")],+ welds=[_weld("KnobWeld", "Door", "Knob")])+++def test_floating_child_is_a_complaint():+ items = geometry_complaints(_with_knob(-0.40)) # 115 mm in front of the door face+ assert len(items) == 1 and "Knob" in items[0] and "away from its parent Door" in items[0]+ assert geometry_complaints(_with_knob(-0.285)) == [] # touching the door face+++def test_door_swinging_into_its_own_cabinet_is_a_complaint():+ """+90° about +z takes the door (which lies along +x from the hinge) to +y: into the carcass."""+ items = geometry_complaints(_cabinet_with_door(lower=0.0, upper=math.pi / 2))+ assert len(items) == 1 and "sweeps" in items[0] and "into Cabinet" in items[0] and "q=1.57 rad" in items[0]+++def _with_wall(x):+ wall = _part("Wall", (x, -0.45, 0.3), (0.06, 0.4, 0.6), attach_to="Cabinet")+ return _cabinet_with_door(extra=[wall], welds=[_weld("WallWeld", "Cabinet", "Wall")])+++def test_door_swinging_into_a_side_wall_is_a_complaint():+ # a wall slab standing outside the cabinet's left face, where the open door (−90°) ends up+ items = geometry_complaints(_with_wall(-0.23))+ assert len(items) == 1 and "sweeps" in items[0] and "into Wall" in items[0], items+ # the same wall on the right face (door never reaches it) is fine+ assert geometry_complaints(_with_wall(0.23)) == []+++def test_drawer_inside_cabinet_is_not_a_collision():+ """A housing that holds the moving part at rest is never a collision candidate — even+ when the drawer front stands 20 mm proud of the carcass."""+ plan = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))+ assert geometry_complaints(plan) == []+ d = plan_example(Track.ARTICULATED_OBJECT)+ drawer = next(p for p in d["parts"] if p["name"] == "Drawer")+ drawer["bbox"]["center"][1] -= 0.02 # front proud of the cabinet+ plan = ArticulatedPlan.model_validate(d)+ cab, drw = (Box.from_bbox(next(p for p in plan.parts if p.name == n).bbox) for n in ("Cabinet", "Drawer"))+ assert HOUSING_FRACTION <= drw.fraction_inside(cab) < 1.0+ assert geometry_complaints(plan) == []+++def test_complaint_text_is_a_reask_with_numbers():+ text = plan_geometry_complaint(_cabinet_with_door(pivot=(0.5, -0.25, 0.3)))+ assert text.startswith("Your plan is valid but its geometry contradicts itself")+ assert "same schema" in text and "- joint DoorHinge" in text+++def test_box_arithmetic():+ a = Box((0, 0, 0), (1, 1, 1))+ b = Box((0.9, 0.9, 0.9), (2, 2, 2))+ assert a.gap_to(b) == 0.0 and abs(a.overlap_depth(b) - 0.1) < 1e-9+ c = Box((1.1, 0, 0), (2, 1, 1))+ assert abs(c.gap_to(a) - 0.1) < 1e-9 and a.overlap_depth(c) < 0+ assert abs(a.dist_to_point((2, 0.5, 0.5)) - 1.0) < 1e-9+ assert ATTACH_GAP_M < COLLISION_MIN_M < PIVOT_TOL_M+++# ------------------------------------------------------------------ sweep aggregation+def _pen(a, b, depth, pose, sev=Severity.ERROR):+ return GateFinding(gate="articulation", severity=sev, target=f"{a}|{b}", message=f"{a}/{b} {depth}",+ fix_hint="shrink", data={"kind": "penetration", "pose": pose, "depth_m": depth})+++def test_aggregate_merges_poses_per_pair_and_ranks_by_depth():+ fs = [_pen("door", "wall", 0.004, {"hinge": 0.5}), _pen("door", "wall", 0.031, {"hinge": 1.5}),+ _pen("door", "wall", 0.002, {}), _pen("lid", "box", 0.010, {"lid_j": 1.0}),+ GateFinding(gate="articulation", severity=Severity.ERROR, target="leg", message="floating",+ data={"kind": "unattached", "pose": {}, "gap_m": 0.05})]+ out = aggregate_findings(fs)+ assert [f.target for f in out] == ["leg", "door|wall", "lid|box"] # gap 0.05 > 0.031 > 0.010+ dw = out[1]+ assert dw.data["n_poses"] == 3 and dw.data["max_depth_m"] == 0.031+ assert "3 of the sampled poses" in dw.message and "31.0 mm" in dw.message and "hinge=1.50" in dw.message+ assert "1 at rest" in dw.message+ assert all(f.severity == Severity.ERROR for f in out)+++def test_aggregate_caps_errors_and_summarises_the_rest():+ fs = [_pen(f"p{i}", "base", 0.001 * (i + 1), {"j": 1.0}) for i in range(MAX_PAIR_FINDINGS + 3)]+ out = aggregate_findings(fs)+ errors = [f for f in out if f.severity == Severity.ERROR]+ warns = [f for f in out if f.severity == Severity.WARN]+ assert len(errors) == MAX_PAIR_FINDINGS and errors[0].target == f"p{MAX_PAIR_FINDINGS + 2}|base"+ assert len(warns) == 1 and warns[0].data["kind"] == "penetration_summary" and "3 more" in warns[0].message+++def test_aggregate_keeps_single_and_warn_findings():+ fs = [_pen("a", "b", 0.001, {}, sev=Severity.WARN)]+ assert aggregate_findings(fs) == fs+ assert aggregate_findings([]) == []