Official Codebase of 3DCodeVerse
Python
review nits: one flag vocabulary, one invariant, docstrings that point instead of restate
ziyao413ca6093ca9
diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.pyindex b75dd454..60174026 100644--- a/harness/codeverse/contracts/common.py+++ b/harness/codeverse/contracts/common.py@@ -208,6 +208,9 @@ class MimicSpec(BaseModel):movable: booltarget: str | None = None # key of the joint this one follows; None = drives itselfmultiplier: float = 1.0+ offset: float = 0.0+ lower: float | None = None # this joint's own limits, when it declares them+ upper: float | None = Noneclass MimicIssue(BaseModel):@@ -217,7 +220,8 @@ class MimicIssue(BaseModel):model_config = ConfigDict(frozen=True)joint: str- kind: Literal["immobile", "zero_multiplier", "self", "unknown_target", "immobile_target", "cycle"]+ kind: Literal["immobile", "zero_multiplier", "self", "unknown_target", "immobile_target",+ "cycle", "out_of_range"]target: strdetail: str = ""@@ -229,7 +233,9 @@ def mimic_issues(specs: Collection[MimicSpec]) -> list[MimicIssue]:``languages/urdf.lint`` and ``spatial.joints_model.load_urdf`` — and they had threecopies of the walk that disagreed on the multiplier floor. The rules live here; eachcaller renders the issues in its own vocabulary (``ValueError`` / gate finding /- ``UrdfError``) and picks the first one when it reports only one.+ ``UrdfError``), picks the first one when it reports only one, and decides what is+ fatal: ``out_of_range`` is a warning in the lint and ignored by the loader, because+ the coupling still poses the mechanism — the follower's own limits are what disagree."""order = list(specs)by_key = {s.key: s for s in order}@@ -250,6 +256,10 @@ def mimic_issues(specs: Collection[MimicSpec]) -> list[MimicIssue]:continueif not src.movable:out.append(MimicIssue(joint=s.name, kind="immobile_target", target=src.name))+ reach = _driven_range(s, src)+ if reach is not None:+ out.append(MimicIssue(joint=s.name, kind="out_of_range", target=src.name,+ detail=f"[{reach[0]:.4g}, {reach[1]:.4g}]"))seen, cur = {s.key}, srcwhile cur.target is not None:if cur.key in seen:@@ -261,3 +271,22 @@ def mimic_issues(specs: Collection[MimicSpec]) -> list[MimicIssue]:break # that joint reports its own unknown target on its own turncur = nxtreturn out+++def _driven_range(follower: MimicSpec, driver: MimicSpec) -> tuple[float, float] | None:+ """Where the coupling actually takes ``follower`` when both declare limits, if that+ is outside the follower's own — ``None`` when it fits or the limits are unknown.++ Slack is 1 % of the follower's span: the one case in 94 recorded couplings+ (wave2_lean, a folding brace) overshot 2.248 against 2.2, which is the multiplier and+ the limit rounded from different numbers rather than a mechanism that jams.+ """+ if None in (follower.lower, follower.upper, driver.lower, driver.upper):+ return None+ ends = (follower.multiplier * driver.lower + follower.offset,+ follower.multiplier * driver.upper + follower.offset)+ lo, hi = min(ends), max(ends)+ slack = max(1e-6, 0.01 * (follower.upper - follower.lower))+ if lo < follower.lower - slack or hi > follower.upper + slack:+ return lo, hi+ return Nonediff --git a/harness/codeverse/languages/urdf/__init__.py b/harness/codeverse/languages/urdf/__init__.pyindex a72fc718..390c0507 100644--- a/harness/codeverse/languages/urdf/__init__.py+++ b/harness/codeverse/languages/urdf/__init__.py@@ -4,6 +4,7 @@ consistency and the ``UrdfBlenderRuntime`` around ``wrappers/run_bpy_links.py``.from __future__ import annotationsimport ast+import contextlibimport jsonimport mathimport os@@ -235,9 +236,14 @@ def _lint_mimics(joints: list[ET.Element], out: list[GateFinding]) -> None:if not jname:continuemovable = el.get("type", "") != "fixed"+ lim = el.find("limit")+ lo = hi = None+ if lim is not None:+ with contextlib.suppress(TypeError, ValueError):+ lo, hi = float(lim.get("lower")), float(lim.get("upper"))mim = el.find("mimic")src = (mim.get("joint") or "").strip() if mim is not None else ""- mult = 1.0+ mult, off = 1.0, 0.0if mim is not None and not src:out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> without joint=", target=jname,fix='<mimic joint="runner_slide" multiplier="1" offset="0"/>'))@@ -245,12 +251,12 @@ def _lint_mimics(joints: list[ET.Element], out: list[GateFinding]) -> None:elif mim is not None:try:mult = float(mim.get("multiplier", 1) or 1)- float(mim.get("offset", 0) or 0)+ off = float(mim.get("offset", 0) or 0)except ValueError:out.append(_f(Severity.ERROR, f"joint '{jname}': <mimic> multiplier/offset must be numbers", target=jname))src = ""- specs.append(MimicSpec(key=jname, name=jname, movable=movable,- target=src or None, multiplier=mult))+ specs.append(MimicSpec(key=jname, name=jname, movable=movable, target=src or None,+ multiplier=mult, offset=off, lower=lo, upper=hi))known = sorted({el.get("name", "") for el in joints if el.get("name")})for i in mimic_issues(specs):j, t = i.joint, i.target@@ -268,6 +274,11 @@ def _lint_mimics(joints: list[ET.Element], out: list[GateFinding]) -> None:elif i.kind == "immobile_target":out.append(_f(Severity.ERROR, f"joint '{j}': mimics '{t}', which is fixed and never moves", target=j,fix="mimic a joint that moves, or give that joint a type and a limit"))+ elif i.kind == "out_of_range":+ out.append(_f(Severity.WARN, f"joint '{j}': following '{t}' drives it over {i.detail}, "+ "outside its own <limit>", target=j,+ fix="Make the limits and the multiplier agree: multiplier * driver range "+ "+ offset is the range this joint really has."))else:out.append(_f(Severity.ERROR, f"joint '{j}': <mimic> chain is a cycle through '{i.detail or j}'",target=j, fix="one joint drives the chain; the rest follow it, directly or in a line"))diff --git a/harness/codeverse/spatial/mcp_server.py b/harness/codeverse/spatial/mcp_server.pyindex d95b5de6..4649ca39 100644--- a/harness/codeverse/spatial/mcp_server.py+++ b/harness/codeverse/spatial/mcp_server.py@@ -74,21 +74,12 @@ def encode_image(path: str, max_side: int = MAX_IMAGE_SIDE) -> str | None:def max_images_for(obs: Observation) -> int:- """Image budget for ONE result, by outcome.-- A tool that could not run ships no image: nothing was rendered that is evidence- about it, and a vendor CLI that receives ``is_error`` stringifies the WHOLE result,- image parts included — gemini-cli's error branch prints- ``safeJsonStringify(rawResponseParts)``, so a 275 kB contact sheet would arrive as- ~366 k characters of base64 TEXT (~261 k prompt tokens) instead of ~516 as an inline- image, and its own 40 000-char truncation does not fire for a multi-part MCP result- (docs/COST.md §30). A FAIL verdict is NOT an error here (``is_error`` is- ``obs.failed``), so it takes the vendor's ordinary image path; it still ships one- image rather than four because the first is the sheet ``image_budget`` keeps, the- rest are per-view repeats of a result the agent is being told to fix, and the- one-image rule is also what keeps the blow-up bounded if ``is_error`` is ever- re-coupled to ``not ok`` (``test_is_error_is_failed_not_the_verdict`` pins that- coupling).+ """Image budget for ONE result, by outcome: none for a call that failed, one for a+ FAIL verdict, ``MAX_IMAGES`` for a pass.++ A failed call ships none because the vendor CLI stringifies an ``is_error`` result+ whole, base64 included — 275 kB of contact sheet arrives as ~261 k prompt tokens of+ text (docs/COST.md §30, which also has the one-image rule's reasoning)."""if obs.failed:return 0diff --git a/harness/codeverse/spatial/registry.py b/harness/codeverse/spatial/registry.pyindex 2338df15..19b64226 100644--- a/harness/codeverse/spatial/registry.py+++ b/harness/codeverse/spatial/registry.py@@ -25,7 +25,7 @@ from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom typing import Any-from pydantic import BaseModel, Field+from pydantic import BaseModel, Field, model_validatorfrom codeverse.workspace import Workspace@@ -35,16 +35,10 @@ class NoArgs(BaseModel):class Observation(BaseModel):- """A tool's answer. ``ok`` is the VERDICT (the gate passed, the build compiled,- nothing penetrates); ``failed`` says the tool could not run at all.-- Only ``failed`` becomes MCP ``is_error`` (``spatial.mcp_server``). Measured over- 224 recorded gemini-cli sessions (selector + full table in docs/COST.md §30): with- ``is_error = not ok``, 62% of 1445 joint_sweep calls, 23% of 2144 builds and ~15%- of the connectivity/contract calls reached the model as broken calls, and the model- retries a broken call — a mean 119k prompt tokens, $0.030 at the measured 73% cache- hit rate. A negative verdict is a result: it keeps ``failed=False`` and leads its- ``text`` with the FAIL verdict instead.+ """A tool's answer: ``ok`` is the VERDICT, ``failed`` says the tool could not run.++ Only ``failed`` becomes MCP ``is_error``; a negative verdict is a result, not a+ broken call (what that cost when the two were one flag: docs/COST.md §30)."""ok: bool = True@@ -55,6 +49,14 @@ class Observation(BaseModel):images: list[str] = Field(default_factory=list, description="PNG paths (small, labelled)")duration_ms: int = 0+ @model_validator(mode="after")+ def _a_failure_is_never_a_pass(self) -> Observation:+ """``failed`` implies ``not ok``: a tool that could not run has no verdict to+ report, and ``Observation(ok=True, failed=True)`` was representable."""+ if self.failed and self.ok:+ raise ValueError("Observation(ok=True, failed=True): a tool that could not run has no verdict")+ return self+@classmethoddef error(cls, text: str, **numbers: Any) -> Observation:"""The tool could not run: every failure caught at the :meth:`ToolDef.call`diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.pyindex e3b3b1ce..1589cd59 100644--- a/harness/codeverse/tracks/planner.py+++ b/harness/codeverse/tracks/planner.py@@ -703,7 +703,10 @@ def restart_note(raw: Any, missing: list[str], budget: PlanBudget) -> str:def restart_enabled() -> bool:- return os.environ.get(PLAN_RESTART_ENV, "1").strip().lower() not in ("0", "false", "off", "no")+ """Kill switch for the degenerate-plan restart, ON by default (docs/COST.md §30)."""+ from codeverse.config import env_flag # ONE flag vocabulary (review-3 S4)++ return env_flag(PLAN_RESTART_ENV, True)def _thin_plan_note(raw: Any, budget: PlanBudget) -> str:diff --git a/harness/tests/spatial_tools/test_mcp_server.py b/harness/tests/spatial_tools/test_mcp_server.pyindex f844cad2..b0e5cdd5 100644--- a/harness/tests/spatial_tools/test_mcp_server.py+++ b/harness/tests/spatial_tools/test_mcp_server.py@@ -8,6 +8,7 @@ import sysfrom pathlib import Pathimport pytest+from pydantic import ValidationErrorfrom codeverse.spatial.mcp_server import build_context, encode_image, main, observation_contentfrom codeverse.spatial.registry import Observation, ToolContext@@ -112,6 +113,18 @@ def test_is_error_is_failed_not_the_verdict(tmp_path: Path) -> None:assert "is_error=obs.failed" in src and "is_error=not obs.ok" not in src+def test_a_failure_cannot_also_be_a_pass() -> None:+ """``failed`` implies ``not ok``. The pair was two independent booleans, so+ ``Observation(ok=True, failed=True)`` was constructible — an is_error result whose+ verdict says the gate passed, which nothing downstream can read consistently."""+++ with pytest.raises(ValidationError, match="has no verdict"):+ Observation(ok=True, failed=True, text="both")+ assert Observation(ok=False, failed=True, text="could not run").failed+ assert not Observation(ok=False, failed=False, text="FAIL: the gate ran").failed++def test_cli_list(stool_ctx: ToolContext, capsys: pytest.CaptureFixture[str]) -> None:assert main(["--workspace", str(stool_ctx.workspace.root), "--list"]) == 0data = json.loads(capsys.readouterr().out)diff --git a/harness/tests/urdf_joints/test_mimic.py b/harness/tests/urdf_joints/test_mimic.pyindex f9354f21..4d9cf891 100644--- a/harness/tests/urdf_joints/test_mimic.py+++ b/harness/tests/urdf_joints/test_mimic.py@@ -269,3 +269,22 @@ def test_an_unknown_target_is_reported_once_not_once_per_follower():MimicSpec(key="b", name="b", movable=True, target="a"),])assert [(i.joint, i.kind) for i in issues] == [("a", "unknown_target")]+++def test_the_lint_warns_when_a_coupling_drives_past_the_follower_s_own_limits(tmp_path):+ """``rib_a_hinge`` is limited to 1.2 and follows a 0–0.3 slide at multiplier 4 — the+ coupling reaches exactly 1.2, so the file that ships is silent. At multiplier 5 it+ reaches 1.5 and the limits and the multiplier disagree; the sweep then poses the joint+ where its own <limit> says it cannot go."""+ from codeverse.workspace import Workspace++ ws = Workspace(tmp_path / "ws").create()+ (ws.src / "model.py").write_text("import bpy\n")+ (ws.src / "robot.urdf").write_text(RIB)+ assert not [f for f in lint_workspace(ws).findings if "drives it over" in f.message]++ (ws.src / "robot.urdf").write_text(RIB.replace('joint="runner_slide" multiplier="4"',+ 'joint="runner_slide" multiplier="5"'))+ warns = [f for f in lint_workspace(ws).findings if "drives it over" in f.message]+ assert len(warns) == 1 and warns[0].severity.value == "warn" and warns[0].target == "rib_a_hinge"+ assert "1.5" in warns[0].message