Official Codebase of 3DCodeVerse
Python
planner: repair the three articulated-plan slips instead of failing the run
ziyaoae321099c756
diff --git a/harness/codeverse/contracts/plan.py b/harness/codeverse/contracts/plan.pyindex 0bad90cf..b3e3c7a6 100644--- a/harness/codeverse/contracts/plan.py+++ b/harness/codeverse/contracts/plan.py@@ -192,6 +192,105 @@ class JointPlan(BaseModel):class ArticulatedPlan(StaticPlan):root_link: strjoints: list[JointPlan] = Field(min_length=1)+ normalisations: list[str] = Field(+ default_factory=list,+ description="filled by the harness, leave empty: automatic corrections applied to the planner's answer "+ "before validation (a sub-part promoted to a link because a joint moves it, a revolute joint "+ "with a > 2π range made continuous, a parent bbox grown around a sub-part)")++ @model_validator(mode="before")+ @classmethod+ def _normalise_raw(cls, data: object) -> object:+ """Repair the three planner mistakes that failed validation twice on compare_art_v2+ (2026-08-25: 5 of 14 articulated prompts, a third of the harness's losses) — each is+ a schema-shaped slip a re-ask did not fix, not a design decision worth a run.++ 1. a joint whose ``parent`` / ``child`` names a SUB-PART: the sub-part is promoted to a+ top-level part (``attach_to`` = its former parent) — anything a joint moves is a link;+ 2. a ``revolute`` joint whose range exceeds 2π becomes ``continuous`` (limits dropped);+ 3. a sub-part sticking out of its parent's bbox by more than the slack: the parent bbox+ grows to enclose it (planner boxes are design intent, not measurements).+ Every repair is recorded in ``normalisations`` so the record shows what the planner+ actually wrote. Anything else still fails validation and is re-asked.+ """+ if not isinstance(data, dict):+ return data+ data = dict(data)+ parts = [dict(p) for p in (data.get("parts") or []) if isinstance(p, dict)]+ joints = [dict(j) for j in (data.get("joints") or []) if isinstance(j, dict)]+ notes: list[str] = list(data.get("normalisations") or [])+ if not parts or not joints:+ return data+ by_name = {to_snake(str(p.get("name", ""))): p for p in parts}++ # 1. joints that move a sub-part → promote it+ referenced = {to_snake(str(j.get(k, ""))) for j in joints for k in ("parent", "child")}+ for part in list(parts):+ kept = []+ for child in part.get("children") or []:+ if not isinstance(child, dict):+ kept.append(child)+ continue+ key = to_snake(str(child.get("name", "")))+ if key in referenced and key not in by_name:+ promoted = {+ "name": child.get("name"), "role": child.get("role") or f"moving part of {part.get('name')}",+ "description": child.get("description", ""), "bbox": child.get("bbox"),+ "material": child.get("material") or part.get("material", ""),+ "attach_to": part.get("name"), "instances": child.get("instances", 1),+ }+ parts.append(promoted)+ by_name[key] = promoted+ notes.append(f"promoted sub-part {part.get('name')}.{child.get('name')} to a link: a joint moves it")+ else:+ kept.append(child)+ part["children"] = kept++ # 2. revolute joints with a > 2π range → continuous+ for j in joints:+ try:+ span = float(j.get("upper", 0.0)) - float(j.get("lower", 0.0))+ except (TypeError, ValueError):+ continue+ if j.get("type") == "revolute" and span > 2 * math.pi + 1e-6:+ j.update(type="continuous", lower=0.0, upper=0.0, rest=0.0)+ notes.append(f"joint {j.get('name')}: revolute range {span:.2f} rad > 2π → continuous")++ # 3. sub-parts outside the parent bbox → grow the parent+ for part in parts:+ bbox = part.get("bbox")+ if not (isinstance(bbox, dict) and isinstance(bbox.get("center"), (list, tuple))+ and isinstance(bbox.get("extents"), (list, tuple))):+ continue+ try:+ lo = [float(c) - float(e) / 2 for c, e in zip(bbox["center"], bbox["extents"], strict=True)]+ hi = [float(c) + float(e) / 2 for c, e in zip(bbox["center"], bbox["extents"], strict=True)]+ except (TypeError, ValueError):+ continue+ grown = False+ for child in part.get("children") or []:+ cb = child.get("bbox") if isinstance(child, dict) else None+ if not (isinstance(cb, dict) and isinstance(cb.get("center"), (list, tuple))+ and isinstance(cb.get("extents"), (list, tuple))):+ continue+ try:+ clo = [float(c) - float(e) / 2 for c, e in zip(cb["center"], cb["extents"], strict=True)]+ chi = [float(c) + float(e) / 2 for c, e in zip(cb["center"], cb["extents"], strict=True)]+ except (TypeError, ValueError):+ continue+ for a in range(3):+ slack = max(SUBPART_SLACK_M, SUBPART_REL_SLACK * abs(hi[a] - lo[a]))+ if lo[a] - clo[a] > slack or chi[a] - hi[a] > slack:+ lo[a], hi[a] = min(lo[a], clo[a]), max(hi[a], chi[a])+ grown = True+ notes.append(f"part {part.get('name')}: bbox grown on {'xyz'[a]} around sub-part "+ f"{child.get('name')}")+ if grown:+ part["bbox"] = {"center": [(lo[a] + hi[a]) / 2 for a in range(3)],+ "extents": [hi[a] - lo[a] for a in range(3)]}++ data["parts"], data["joints"], data["normalisations"] = parts, joints, notes+ return data@model_validator(mode="after")def _tree(self) -> ArticulatedPlan:diff --git a/harness/codeverse/prompts/tracks/plan_articulated.j2 b/harness/codeverse/prompts/tracks/plan_articulated.j2index 5f8fac0b..823b5025 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".+ * `parent` / `child` name top-level `parts` (links) — NEVER a sub-part: anything a joint moves must be+ its 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`.6. `acceptance` — 6 to 12 items: dimensions (`measure`), ground contact, each key feature(`visual`), and ONE `articulation` item per joint ("drawer slides out 0.35 m without touching thecabinet", "door swings 90° about the left edge, no penetration through the range").diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.pyindex aecb1c76..0e8dce47 100644--- a/harness/codeverse/tracks/planner.py+++ b/harness/codeverse/tracks/planner.py@@ -48,7 +48,7 @@ P = TypeVar("P", bound=BaseModel)#: re-ask budgets — a plan the SCHEMA rejects and a plan the QUALITY gate rejects are#: different failures and get separate chances (see ``plan_with_usage``).-MAX_VALIDATION_REASKS = 1+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#: 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@@ -86,7 +86,7 @@ PLAN_TEMPLATES: dict[Track, str] = {class PlanningError(RuntimeError):- """The planner could not produce a valid plan after one re-ask.+ """The planner could not produce a valid plan after MAX_VALIDATION_REASKS re-asks.Carries the ``usage`` already spent so callers can charge the budget evenwhen planning fails (a failed re-ask is still paid for)."""@@ -214,6 +214,9 @@ 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+ normalised = 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])result = finalise(result) if finalise is not None else ensure_acceptance(normalise_names(result), spec)result = enrich_plan(result, brief, budget)ws.write_json(ws.plan_path, result)diff --git a/harness/tests/core/test_plan_normalise.py b/harness/tests/core/test_plan_normalise.pynew file mode 100644index 00000000..7882d840--- /dev/null+++ b/harness/tests/core/test_plan_normalise.py@@ -0,0 +1,77 @@+"""ArticulatedPlan._normalise_raw: the three planner slips that cost compare_art_v2 5 of 14 prompts."""++from __future__ import annotations++import copy+import math++import pytest+from pydantic import ValidationError++from codeverse.contracts.common import Track+from codeverse.contracts.plan import ArticulatedPlan+from codeverse.tracks.planner import plan_example+++def _raw() -> dict:+ d = copy.deepcopy(plan_example(Track.ARTICULATED_OBJECT))+ assert ArticulatedPlan.model_validate(d).normalisations == []+ return d+++def test_a_valid_plan_is_untouched():+ d = _raw()+ p = ArticulatedPlan.model_validate(copy.deepcopy(d))+ assert p.normalisations == [] and [x.name for x in p.parts] == [x["name"] for x in d["parts"]]+++def test_a_joint_that_moves_a_sub_part_promotes_it_to_a_link():+ d = _raw()+ parent = d["parts"][0]+ sash = {"name": "UpperSash", "role": "sliding sash", "description": "a 0.60 x 0.55 m frame with a pane",+ "bbox": {"center": list(parent["bbox"]["center"]), "extents": [e * 0.5 for e in parent["bbox"]["extents"]]},+ "material": "painted pine"}+ parent.setdefault("children", []).append(sash)+ d["joints"].append({"name": "UpperSashSlide", "type": "prismatic", "parent": parent["name"], "child": "UpperSash",+ "axis": [0, 0, 1], "pivot": [0, 0, 0.5], "lower": 0.0, "upper": 0.3, "rest": 0.0,+ "motion": "upper sash slides up"})+ p = ArticulatedPlan.model_validate(d)+ names = [x.name for x in p.parts]+ assert "UpperSash" in names+ promoted = next(x for x in p.parts if x.name == "UpperSash")+ assert promoted.attach_to == parent["name"] and promoted.material == "painted pine"+ assert all(c.name != "UpperSash" for x in p.parts for c in x.children)+ assert any("promoted sub-part" in n and "UpperSash" in n for n in p.normalisations)+++def test_a_revolute_joint_over_two_pi_becomes_continuous():+ d = _raw()+ j = d["joints"][0]+ j.update(type="revolute", lower=0.0, upper=4 * math.pi, rest=0.0)+ p = ArticulatedPlan.model_validate(d)+ fixed = next(x for x in p.joints if x.name == j["name"])+ assert fixed.type == "continuous" and fixed.lower == fixed.upper == 0.0+ assert any("> 2π → continuous" in n for n in p.normalisations)+++def test_a_sub_part_outside_its_parent_grows_the_parent_bbox():+ d = _raw()+ parent = d["parts"][0]+ c, e = parent["bbox"]["center"], parent["bbox"]["extents"]+ sill = {"name": "ThresholdSill", "role": "sill", "description": "a 40 mm deep sill proud of the frame",+ # 0.20 m proud of the frame: far outside any slack (max(SUBPART_SLACK_M, 10 % of the extent))+ "bbox": {"center": [c[0], c[1] - e[1] / 2 - 0.20, c[2] - e[2] / 2 + 0.02], "extents": [e[0], 0.06, 0.04]}}+ parent.setdefault("children", []).append(sill)+ p = ArticulatedPlan.model_validate(d)+ grown = next(x for x in p.parts if x.name == parent["name"])+ assert grown.bbox.min[1] <= sill["bbox"]["center"][1] - 0.03 + 1e-9 # the parent now encloses the sill+ assert grown.bbox.max[1] == pytest.approx(c[1] + e[1] / 2) # and did not grow where it did not need to+ assert any("bbox grown on y" in n for n in p.normalisations)+++def test_unfixable_plans_still_fail():+ d = _raw()+ d["joints"].append({"name": "Ghost", "type": "fixed", "parent": d["parts"][0]["name"], "child": "NoSuchLink",+ "axis": [0, 0, 1], "pivot": [0, 0, 0]})+ with pytest.raises(ValidationError, match="unknown link"):+ ArticulatedPlan.model_validate(d)diff --git a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py b/harness/tests/orchestrator_tracks/test_generation_planner_repair.pyindex 45d6657d..4d92ac34 100644--- a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py+++ b/harness/tests/orchestrator_tracks/test_generation_planner_repair.py@@ -195,6 +195,19 @@ def test_planner_gives_up_after_reask(tmp_ws):model = FakeChatModel(lambda req: {"bad": 1})with pytest.raises(PlanningError):plan(make_spec(), "fake:planner", StaticPlan, tmp_ws, model=model)+ from codeverse.tracks.planner import MAX_VALIDATION_REASKS++ assert len(model.requests) == 1 + MAX_VALIDATION_REASKS == 3+++def test_planner_allows_two_validation_reasks(tmp_ws):+ """compare_art_v2: 5 of 14 articulated plans failed validation twice and the run died.+ A second validation re-ask is cheap next to the run it saves."""+ answers = [{"object_name": "X"}, {"object_name": "Y"}, _valid_plan_dict()]+ model = FakeChatModel(lambda req: answers.pop(0))+ p = plan(make_spec(), "fake:planner", StaticPlan, tmp_ws, model=model, runtime=FakeRuntime(Language.THREEJS))+ assert p.object_name == "DiningChair" and len(model.requests) == 3+ assert all("failed validation" in r.messages[-1].text for r in model.requests[1:])def test_planner_scene_example_validates_and_prompts_render():