Official Codebase of 3DCodeVerse
Python
tracks: fold six single-importer satellites back into their consumers (35→28 files)
gaoypeng6aa08e41d527
diff --git a/harness/codeverse/orchestrator/candidates.py b/harness/codeverse/orchestrator/candidates.pydeleted file mode 100644index 929c4dc7..00000000--- a/harness/codeverse/orchestrator/candidates.py+++ /dev/null@@ -1,118 +0,0 @@-"""Choosing between alternatives: best-of-N candidates and pairwise tie-breaks.--Pure decision logic (no I/O, no models) shared by the tracks:--* ``CandidateRecord`` — what one baseline candidate produced (commit, quick- score, gate errors, cost); ``rank_candidates`` orders them.-* ``decide_best`` — when a new round's score is within ``margin`` of the- current best the absolute delta is judge noise (flash judges compress their- score range), so a position-swapped pairwise comparison decides; the new- round replaces the best only when it wins with enough confidence.-"""--from __future__ import annotations--import logging-from collections.abc import Callable, Sequence-from typing import Any, Literal--from pydantic import BaseModel, Field--from codeverse.contracts.common import Usage--log = logging.getLogger(__name__)---class CandidateRecord(BaseModel):- """One best-of-N baseline candidate (generated in its own sub-workspace)."""-- index: int- label: str- commit: str = Field(default="", description="commit in the candidate's sub-workspace")- workspace: str = ""- build_ok: bool = False- score: float | None = None- gate_errors: int = 0- usage: Usage = Field(default_factory=Usage)- duration_s: float = 0.0- sheet: str = Field(default="", description="quick contact sheet (4 views) used for the quick judge")- notes: str = ""- selected: bool = False-- def sort_key(self) -> tuple[int, float, int, int]:- return (1 if self.build_ok else 0, self.score if self.score is not None else -1.0, -self.gate_errors, -self.index)---def rank_candidates(records: Sequence[CandidateRecord]) -> list[int]:- """Candidate indices best-first: built > higher quick score > fewer gate errors > earlier."""- return [r.index for r in sorted(records, key=lambda r: r.sort_key(), reverse=True)]---class PairwiseNote(BaseModel):- """What a tie-break compared and what it concluded (persisted in round notes)."""-- a: str = Field(description="label of the incumbent (current best)")- b: str = Field(description="label of the challenger (new round / other candidate)")- winner: Literal["a", "b", "tie"] = "tie"- confidence: float = 0.0- accepted: bool = Field(default=False, description="True when the challenger replaces the incumbent")- reasons: list[str] = Field(default_factory=list)- usage: Usage = Field(default_factory=Usage)- error: str = ""-- def line(self) -> str:- verdict = {"a": f"{self.a} wins", "b": f"{self.b} wins", "tie": "tie"}[self.winner]- return f"pairwise {self.a} vs {self.b}: {verdict} (confidence {self.confidence:.2f}) → {'replace' if self.accepted else 'keep'}"---Decision = Literal["score", "pairwise", "keep"]--#: ``compare()`` → any object with ``winner`` ('a'|'b'|'tie'), ``confidence``, ``reasons``, ``usage``.-CompareFn = Callable[[], Any]---def within_margin(a: float | None, b: float | None, margin: float) -> bool:- return a is not None and b is not None and abs(a - b) <= margin---def decide_best(- incumbent_score: float | None,- challenger_score: float | None,- *,- margin: float,- min_confidence: float,- compare: CompareFn | None,- labels: tuple[str, str] = ("best", "new"),-) -> tuple[Decision, PairwiseNote | None]:- """Should the challenger replace the incumbent?-- * scores differ by more than ``margin`` → ``"score"`` (caller uses the- ordinary ranking rule);- * within the margin and ``compare`` given → run it; ``"pairwise"`` when the- challenger wins with ``confidence ≥ min_confidence``, else ``"keep"``;- * within the margin without a comparator → ``"keep"`` (ties go to the- incumbent: fewer regenerations, stable best commit).- """- if incumbent_score is None or challenger_score is None:- return "score", None- if not within_margin(incumbent_score, challenger_score, margin):- return "score", None- note = PairwiseNote(a=labels[0], b=labels[1])- if compare is None:- return "keep", note- try:- res = compare()- except Exception as e: # noqa: BLE001 — a judge outage must not pick a worse round- log.warning("pairwise tie-break failed: %s", e)- note.error = f"{type(e).__name__}: {e}"- return "keep", note- note.winner = getattr(res, "winner", "tie")- note.confidence = float(getattr(res, "confidence", 0.0) or 0.0)- note.reasons = list(getattr(res, "reasons", []) or [])[:6]- note.usage = getattr(res, "usage", None) or Usage()- note.error = getattr(res, "error", "") or ""- note.accepted = note.winner == "b" and note.confidence >= min_confidence- return ("pairwise" if note.accepted else "keep"), note---__all__ = ["CandidateRecord", "CompareFn", "Decision", "PairwiseNote", "decide_best", "rank_candidates", "within_margin"]diff --git a/harness/codeverse/tracks/__init__.py b/harness/codeverse/tracks/__init__.pyindex 70e9cb22..7cceec7c 100644--- a/harness/codeverse/tracks/__init__.py+++ b/harness/codeverse/tracks/__init__.py@@ -1,5 +1,53 @@-"""Tracks: static_object · articulated_object · scene. ``get_track(Track.X)``."""+"""Tracks: static_object · articulated_object · scene · graphics.++``get_track(Track.X)`` builds the pipeline; ``TrackPipeline`` is the protocol the+orchestrator drives. (Formerly ``tracks/base.py`` — folded into the package root+2026-08-28: its only importer was this ``__init__``.)+"""++from __future__ import annotations++from typing import Any, Protocol++from codeverse.contracts.common import Track+from codeverse.contracts.plan import Plan+from codeverse.contracts.run import RunRecord+from codeverse.contracts.spec import Spec+from codeverse.workspace import Workspace+++class TrackPipeline(Protocol):+ track: Track+ rubric: str # judges/rubrics/<rubric>.yaml++ def plan(self, spec: Spec, ws: Workspace) -> Plan:+ """Planner model call(s) → validated Plan (re-asked on validation errors)."""+ ...++ def run(self, spec: Spec, ws: Workspace, *, resume: bool = False) -> RunRecord:+ """Full pipeline: plan → baseline → rounds → finalise. Must be resumable."""+ ...+++def get_track(track: Track | str, **options: Any) -> TrackPipeline:+ """Track instance for ``track``. ``options`` are forwarded to the track+ constructor (e.g. ``n_candidates=2`` for a best-of-N baseline, ``policy=``)."""+ t = Track(track)+ if t is Track.STATIC_OBJECT:+ from codeverse.tracks.static_object import StaticObjectTrack++ return StaticObjectTrack(**options)+ if t is Track.ARTICULATED_OBJECT:+ from codeverse.tracks.articulated_object import ArticulatedObjectTrack++ return ArticulatedObjectTrack(**options)+ if t is Track.GRAPHICS:+ from codeverse.tracks.graphics import GraphicsTrack++ return GraphicsTrack(**options)+ from codeverse.tracks.scene import SceneTrack++ return SceneTrack(**options)-from codeverse.tracks.base import TrackPipeline, get_track__all__ = ["TrackPipeline", "get_track"]diff --git a/harness/codeverse/tracks/articulated_object.py b/harness/codeverse/tracks/articulated_object.pyindex b427d9d7..e7f4f88f 100644--- a/harness/codeverse/tracks/articulated_object.py+++ b/harness/codeverse/tracks/articulated_object.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport loggingimport time+from collections.abc import Sequencefrom pathlib import Pathfrom codeverse.contracts.artifacts import (@@ -23,9 +24,9 @@ from codeverse.contracts.artifacts import ()from codeverse.contracts.common import TRACK_INFO, Trackfrom codeverse.contracts.plan import ArticulatedPlan, Plan+from codeverse.conventions import to_snakefrom codeverse.spatial.render import RenderErrorfrom codeverse.tracks.common import RunContext-from codeverse.tracks.motion import MOTION_GATEfrom codeverse.tracks.static_object import ObjectPipeline, StaticObjectTrackfrom codeverse.workspace import Workspace@@ -152,3 +153,122 @@ def _find_urdf(ws: Workspace) -> Path | None:if cand.is_file():return candreturn None+++# ===================================================================== planned-motion gate+# (merged from codeverse/tracks/motion.py, 2026-08-28 — its two importers were this file+# and one lazy Services hook; the byte-identical _find_urdf duplicate died with it)+MOTION_GATE = "motion_direction"++#: phrase → direction key understood by ``spatial.joints.motion_direction_check``.+#: Longer phrases first so "pulls out" wins over "out"; explicit axes first of all.+_PHRASES: tuple[tuple[str, str], ...] = (+ ("-y", "-y"), ("+y", "+y"), ("-z", "-z"), ("+z", "+z"), ("-x", "-x"), ("+x", "+x"),+ ("towards the front", "front"), ("toward the front", "front"), ("to the front", "front"),+ ("opens to the front", "front"), ("opens out", "front"), ("pulls out", "front"), ("slides out", "front"),+ ("pull out", "front"), ("slide out", "front"), ("swings out", "front"), ("outward", "front"), ("forward", "front"),+ ("towards the viewer", "front"), ("toward the viewer", "front"), ("frontward", "front"),+ ("towards the back", "back"), ("toward the back", "back"), ("to the back", "back"), ("pushes in", "back"),+ ("slides in", "back"), ("backward", "back"), ("rearward", "back"), ("inward", "back"),+ ("upward", "up"), ("upwards", "up"), ("opens up", "up"), ("lifts", "up"), ("lift", "up"), ("raises", "up"),+ ("raise", "up"), ("rises", "up"),+ ("downward", "down"), ("downwards", "down"), ("lowers", "down"), ("drops", "down"),+ ("folds down", "down"), ("opens down", "down"),+ ("to the left", "left"), ("leftward", "left"), ("swings left", "left"),+ ("to the right", "right"), ("rightward", "right"), ("swings right", "right"),+ ("front", "front"), ("back", "back"), ("up", "up"), ("down", "down"), ("left", "left"), ("right", "right"),+ ("out", "front"),+)++_SKIP_MARKERS = ("not ", "n't", "either", "both", "around", "rotates about", "spins")+_DIR_GROUPS = {"front": "y", "back": "y", "-y": "y", "+y": "y", "up": "z", "down": "z", "+z": "z", "-z": "z",+ "left": "x", "right": "x", "-x": "x", "+x": "x"}+++def expected_direction(motion: str) -> str | None:+ """Direction key for an obvious motion description, else ``None``.++ Rules: explicit signed axes win; otherwise the first (longest) phrase hit;+ text naming two different axes ("up and to the left"), negations or pure+ rotations ("spins around its axis") → ``None`` (ambiguous — skip)."""+ text = " ".join((motion or "").lower().replace("_", " ").split())+ if not text or any(m in text for m in _SKIP_MARKERS):+ return None+ padded = f" {text} "+ hits: list[str] = []+ for phrase, key in _PHRASES:+ if _contains_word(padded, phrase):+ hits.append(key)+ if key in ("-y", "+y", "-z", "+z", "-x", "+x"):+ return key+ if not hits:+ return None+ axes = {_DIR_GROUPS[h] for h in hits}+ if len(axes) > 1:+ # "opens up and out" — up/front conflict: the longest phrase decides only if one axis dominates+ first_axis = _DIR_GROUPS[hits[0]]+ if any(_DIR_GROUPS[h] != first_axis for h in hits[1:]):+ return None+ return hits[0]+++def _contains_word(padded: str, phrase: str) -> bool:+ """Whole-word containment (phrase boundaries are spaces or punctuation)."""+ i = padded.find(phrase)+ while i >= 0:+ before = padded[i - 1] if i > 0 else " "+ after = padded[i + len(phrase)] if i + len(phrase) < len(padded) else " "+ if not before.isalnum() and not after.isalnum():+ return True+ i = padded.find(phrase, i + 1)+ return False+++def axis_fix_hint(joint_name: str, axis: Sequence[float] | None, expected: str) -> str:+ if axis is not None and len(axis) == 3:+ neg = tuple(-float(a) for a in axis)+ return (f"in src/robot.urdf set joint '{joint_name}' <axis xyz=\"{neg[0]:g} {neg[1]:g} {neg[2]:g}\"/> "+ f"(negate the axis) — or swap lower/upper so positive motion goes {expected}")+ return f"negate the <axis> of joint '{joint_name}' in src/robot.urdf (or swap lower/upper) so motion goes {expected}"+++def default_motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None:+ """Run ``motion_direction_check`` for every plan joint with an obvious motion+ direction. ``None`` when the plan has no such joints; unknown joints /+ missing meshes are WARN findings (the sweep gate already reports them)."""+ joints = list(getattr(plan, "joints", None) or [])+ wanted = [(j, expected_direction(j.motion)) for j in joints]+ wanted = [(j, d) for j, d in wanted if d is not None]+ if not wanted:+ return None+ from codeverse.spatial import joints as sj++ urdf = _find_urdf(ws)+ if urdf is None:+ return None+ t0 = time.time()+ findings: list[GateFinding] = []+ try:+ robot = sj.load_urdf(urdf, ws.artifacts / "meshes")+ except sj.UrdfError as e:+ return GateReport(gate=MOTION_GATE, passed=True, findings=[GateFinding(+ gate=MOTION_GATE, severity=Severity.WARN, target="robot.urdf", message=f"motion checks skipped: {e}")])+ urdf_names = {to_snake(n): n for n in getattr(robot, "joints", {})}+ for j, expected in wanted:+ name = urdf_names.get(to_snake(j.name), j.name) # URDF joint named like the plan joint (any casing)+ try:+ chk = sj.motion_direction_check(robot, name, expected)+ except sj.UrdfError as e:+ findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.WARN, target=j.name,+ message=f"motion check skipped: {e}", data={"expected": expected}))+ continue+ data = {"expected": expected, "observed_dir": list(chk.observed_dir), "motion": j.motion}+ if chk.ok:+ findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.INFO, target=j.name, message=chk.message, data=data))+ else:+ findings.append(GateFinding(+ gate=MOTION_GATE, severity=Severity.ERROR, target=j.name,+ message=f"{chk.message}. Plan says: \"{j.motion}\"",+ fix_hint=axis_fix_hint(j.name, getattr(j, "axis", None), expected), data=data))+ return GateReport(gate=MOTION_GATE, passed=not any(f.severity == Severity.ERROR for f in findings),+ findings=findings, duration_ms=int((time.time() - t0) * 1000))diff --git a/harness/codeverse/tracks/base.py b/harness/codeverse/tracks/base.pydeleted file mode 100644index a15d05d4..00000000--- a/harness/codeverse/tracks/base.py+++ /dev/null@@ -1,45 +0,0 @@-"""Track protocol: what every pipeline must provide to the orchestrator."""--from __future__ import annotations--from typing import Any, Protocol--from codeverse.contracts.common import Track-from codeverse.contracts.plan import Plan-from codeverse.contracts.run import RunRecord-from codeverse.contracts.spec import Spec-from codeverse.workspace import Workspace---class TrackPipeline(Protocol):- track: Track- rubric: str # judges/rubrics/<rubric>.yaml-- def plan(self, spec: Spec, ws: Workspace) -> Plan:- """Planner model call(s) → validated Plan (re-asked on validation errors)."""- ...-- def run(self, spec: Spec, ws: Workspace, *, resume: bool = False) -> RunRecord:- """Full pipeline: plan → baseline → rounds → finalise. Must be resumable."""- ...---def get_track(track: Track | str, **options: Any) -> TrackPipeline:- """Track instance for ``track``. ``options`` are forwarded to the track- constructor (e.g. ``n_candidates=2`` for a best-of-N baseline, ``policy=``)."""- t = Track(track)- if t is Track.STATIC_OBJECT:- from codeverse.tracks.static_object import StaticObjectTrack-- return StaticObjectTrack(**options)- if t is Track.ARTICULATED_OBJECT:- from codeverse.tracks.articulated_object import ArticulatedObjectTrack-- return ArticulatedObjectTrack(**options)- if t is Track.GRAPHICS:- from codeverse.tracks.graphics import GraphicsTrack-- return GraphicsTrack(**options)- from codeverse.tracks.scene import SceneTrack-- return SceneTrack(**options)diff --git a/harness/codeverse/tracks/candidates.py b/harness/codeverse/tracks/candidates.pyindex 16965acf..76c2e98b 100644--- a/harness/codeverse/tracks/candidates.py+++ b/harness/codeverse/tracks/candidates.py@@ -19,10 +19,12 @@ from __future__ import annotationsimport loggingimport shutilimport time-from collections.abc import Sequence+from collections.abc import Callable, Sequencefrom dataclasses import replacefrom pathlib import Path-from typing import Any+from typing import Any, Literal++from pydantic import BaseModel, Fieldfrom codeverse.contracts.artifacts import GateReport, RenderSetfrom codeverse.contracts.common import Usage@@ -30,12 +32,6 @@ from codeverse.contracts.run import RoundRecordfrom codeverse.conventions import OBJECT_VIEWS_QUICKfrom codeverse.fanout import fan_outfrom codeverse.orchestrator.budget import BudgetExceeded-from codeverse.orchestrator.candidates import (- CandidateRecord,- PairwiseNote,- decide_best,- rank_candidates,-)from codeverse.orchestrator.rounds import BestSelectorfrom codeverse.tracks.common import RunContextfrom codeverse.tracks.generation import GenerationTask@@ -326,3 +322,98 @@ def _pairwise_fn(ctx: RunContext, renders_a: RenderSet | None, renders_b: Render__all__ = ["CAND_DIR", "adopt_candidate", "choose_best_round", "make_candidate_context", "run_best_of_n", "run_candidate","select_candidate"]+++# ===================================================================== decision logic+# (merged from codeverse/orchestrator/candidates.py, 2026-08-28 — this file was its+# only production importer, and two candidates.py in sibling packages was a hazard)+class CandidateRecord(BaseModel):+ """One best-of-N baseline candidate (generated in its own sub-workspace)."""++ index: int+ label: str+ commit: str = Field(default="", description="commit in the candidate's sub-workspace")+ workspace: str = ""+ build_ok: bool = False+ score: float | None = None+ gate_errors: int = 0+ usage: Usage = Field(default_factory=Usage)+ duration_s: float = 0.0+ sheet: str = Field(default="", description="quick contact sheet (4 views) used for the quick judge")+ notes: str = ""+ selected: bool = False++ def sort_key(self) -> tuple[int, float, int, int]:+ return (1 if self.build_ok else 0, self.score if self.score is not None else -1.0, -self.gate_errors, -self.index)+++def rank_candidates(records: Sequence[CandidateRecord]) -> list[int]:+ """Candidate indices best-first: built > higher quick score > fewer gate errors > earlier."""+ return [r.index for r in sorted(records, key=lambda r: r.sort_key(), reverse=True)]+++class PairwiseNote(BaseModel):+ """What a tie-break compared and what it concluded (persisted in round notes)."""++ a: str = Field(description="label of the incumbent (current best)")+ b: str = Field(description="label of the challenger (new round / other candidate)")+ winner: Literal["a", "b", "tie"] = "tie"+ confidence: float = 0.0+ accepted: bool = Field(default=False, description="True when the challenger replaces the incumbent")+ reasons: list[str] = Field(default_factory=list)+ usage: Usage = Field(default_factory=Usage)+ error: str = ""++ def line(self) -> str:+ verdict = {"a": f"{self.a} wins", "b": f"{self.b} wins", "tie": "tie"}[self.winner]+ return f"pairwise {self.a} vs {self.b}: {verdict} (confidence {self.confidence:.2f}) → {'replace' if self.accepted else 'keep'}"+++Decision = Literal["score", "pairwise", "keep"]++#: ``compare()`` → any object with ``winner`` ('a'|'b'|'tie'), ``confidence``, ``reasons``, ``usage``.+CompareFn = Callable[[], Any]+++def within_margin(a: float | None, b: float | None, margin: float) -> bool:+ return a is not None and b is not None and abs(a - b) <= margin+++def decide_best(+ incumbent_score: float | None,+ challenger_score: float | None,+ *,+ margin: float,+ min_confidence: float,+ compare: CompareFn | None,+ labels: tuple[str, str] = ("best", "new"),+) -> tuple[Decision, PairwiseNote | None]:+ """Should the challenger replace the incumbent?++ * scores differ by more than ``margin`` → ``"score"`` (caller uses the+ ordinary ranking rule);+ * within the margin and ``compare`` given → run it; ``"pairwise"`` when the+ challenger wins with ``confidence ≥ min_confidence``, else ``"keep"``;+ * within the margin without a comparator → ``"keep"`` (ties go to the+ incumbent: fewer regenerations, stable best commit).+ """+ if incumbent_score is None or challenger_score is None:+ return "score", None+ if not within_margin(incumbent_score, challenger_score, margin):+ return "score", None+ note = PairwiseNote(a=labels[0], b=labels[1])+ if compare is None:+ return "keep", note+ try:+ res = compare()+ except Exception as e: # noqa: BLE001 — a judge outage must not pick a worse round+ log.warning("pairwise tie-break failed: %s", e)+ note.error = f"{type(e).__name__}: {e}"+ return "keep", note+ note.winner = getattr(res, "winner", "tie")+ note.confidence = float(getattr(res, "confidence", 0.0) or 0.0)+ note.reasons = list(getattr(res, "reasons", []) or [])[:6]+ note.usage = getattr(res, "usage", None) or Usage()+ note.error = getattr(res, "error", "") or ""+ note.accepted = note.winner == "b" and note.confidence >= min_confidence+ return ("pairwise" if note.accepted else "keep"), notediff --git a/harness/codeverse/tracks/common.py b/harness/codeverse/tracks/common.pyindex 04dae8bc..1125efc6 100644--- a/harness/codeverse/tracks/common.py+++ b/harness/codeverse/tracks/common.py@@ -127,8 +127,8 @@ class Services:return _import("codeverse.spatial.silhouette", "compare_silhouette")(render_png, reference_png)def motion_checks(self, ws: Workspace, plan: Plan) -> GateReport | None:- """Planned joint motion text vs the built URDF's actual motion direction. See tracks/motion.py."""- from codeverse.tracks.motion import default_motion_checks+ """Planned joint motion text vs the built URDF's actual motion direction."""+ from codeverse.tracks.articulated_object import default_motion_checksreturn default_motion_checks(ws, plan)diff --git a/harness/codeverse/tracks/detailing.py b/harness/codeverse/tracks/detailing.pydeleted file mode 100644index 1120eedd..00000000--- a/harness/codeverse/tracks/detailing.py+++ /dev/null@@ -1,162 +0,0 @@-"""The DETAIL round: surface detail without moving anything.--Measured on the recorded corpus (wave "generation-depth"): across 88 consecutive-refine-round pairs the built part count never changed and mean Δgeometry_detail-was **+0.003** — the refine loop is a repair loop. The rounds that *did* add-geometry added it while assembly was still broken and paid for it: > 2000 tris-added → Δassembly_fit −0.075 / Δoverall −0.025, against +0.078 / +0.092 for-rounds that changed ≤ 200 triangles.--So detail gets its own round kind, offered only once the structure gates are-clean (``orchestrator.rounds.detail_blocked``), with one promise — the silhouette,-the placement and the part list do not move — and one deterministic gate that-checks the promise (:func:`drift_gate`).-"""--from __future__ import annotations--from typing import Any--from codeverse.conventions import LANGUAGE_FRAME, Frame, to_pascal, to_snake--# --------------------------------------------------------------------------- detail-round drift gate-DRIFT_GATE = "detail_drift"---def drift_findings(before: Any, after: Any, *, tol_m: float, language: str = "") -> list[Any]:- """Did a detail round move anything? Findings for the ``detail_drift`` gate.-- The detail round's whole contract is "surface only": the silhouette, the part- list and every part box stay put. This is the deterministic check of that- promise — the judge is never asked whether the shape moved, code answers it.- """- from codeverse.contracts.artifacts import GateFinding, Severity-- out: list[Any] = []- if before is None or after is None:- return out- for axis, a, b in zip(_axes(language), before.extents, after.extents, strict=True):- d = float(b) - float(a)- if abs(d) > tol_m:- out.append(GateFinding(- gate=DRIFT_GATE, severity=Severity.ERROR, target="overall",- message=f"the detail round changed the overall {axis} extent by {d * 1000:+.1f} mm "- f"({a:.3f} → {b:.3f} m); a detail round may not change the silhouette",- fix_hint="revert whatever grew the object (a bevel that widened a part, a fastener sticking out) "- "and keep the added geometry inside the existing surfaces",- data={"kind": "detail_drift", "axis": axis, "delta_m": round(d, 5)}))- was = {to_snake(str(p.name)): p for p in (before.parts or ())}- now = {to_snake(str(p.name)): p for p in (after.parts or ())}- for key in sorted(set(was) - set(now)):- out.append(GateFinding(- gate=DRIFT_GATE, severity=Severity.ERROR, target=to_pascal(key),- message=f"part '{to_pascal(key)}' disappeared during the detail round",- fix_hint=f"restore '{to_pascal(key)}' exactly as it was before this round",- data={"kind": "detail_drift", "removed": key}))- for key in sorted(set(now) - set(was)):- out.append(GateFinding(- gate=DRIFT_GATE, severity=Severity.WARN, target=to_pascal(key),- message=f"the detail round introduced a new top-level part '{to_pascal(key)}'",- fix_hint="detail belongs inside an existing part; merge it into the part it decorates "- "(or accept it only if the plan names it)",- data={"kind": "detail_drift", "added": key}))- moved = 0- for key in sorted(set(was) & set(now)):- a, b = was[key], now[key]- dc = max(abs((bl + bh) / 2 - (al + ah) / 2)- for al, ah, bl, bh in zip(a.bbox_min, a.bbox_max, b.bbox_min, b.bbox_max, strict=True))- de = max(abs((bh - bl) - (ah - al))- for al, ah, bl, bh in zip(a.bbox_min, a.bbox_max, b.bbox_min, b.bbox_max, strict=True))- if max(dc, de) <= tol_m:- continue- moved += 1- if moved > 8:- continue- out.append(GateFinding(- gate=DRIFT_GATE, severity=Severity.ERROR, target=to_pascal(key),- message=f"part '{to_pascal(key)}' moved {dc * 1000:.1f} mm / resized {de * 1000:.1f} mm during the "- f"detail round (tolerance {tol_m * 1000:.0f} mm)",- fix_hint="put the part back on its previous centre and extents; add the detail inside that box",- data={"kind": "detail_drift", "part": key, "centre_mm": round(dc * 1000, 2),- "extent_mm": round(de * 1000, 2)}))- if moved > 8:- out.append(GateFinding(gate=DRIFT_GATE, severity=Severity.ERROR, target="overall",- message=f"{moved} parts moved during the detail round ({moved - 8} more not listed)",- fix_hint="revert the placement changes; this round may only add surface geometry",- data={"kind": "detail_drift", "moved": moved}))- if not out:- d_tri = int(getattr(after, "tri_count", 0) or 0) - int(getattr(before, "tri_count", 0) or 0)- out.append(GateFinding(gate=DRIFT_GATE, severity=Severity.INFO, target="overall",- message=f"detail round held the contract: no part moved more than "- f"{tol_m * 1000:.0f} mm; {d_tri:+,} triangles added",- data={"kind": "detail_drift", "delta_tris": d_tri}))- return out---def _axes(language: str) -> tuple[str, str, str]:- """Axis letters as the AUTHOR sees them. ``Measurement.extents`` is in the GLB frame- (Y-up); a blender/cadquery/urdf author thinks Z-up, where glb (x, y, z) reads (x, z, y)- — so naming the GLB axis in a fix hint would send them to the wrong dimension."""- if LANGUAGE_FRAME.get(language) is Frame.Z_UP_NEG_Y_FRONT:- return ("x", "z", "y")- return ("x", "y", "z")---def drift_gate(before: Any, after: Any, *, tol_m: float, language: str = "") -> Any:- """``detail_drift`` GateReport (passing when nothing moved)."""- from codeverse.contracts.artifacts import GateReport, Severity-- findings = drift_findings(before, after, tol_m=tol_m, language=language)- return GateReport(gate=DRIFT_GATE, findings=findings,- passed=not any(f.severity is Severity.ERROR for f in findings))---# --------------------------------------------------------------------------- detail-round tasks-#: judge improvement-plan kinds a DETAIL round is allowed to act on. Assembly/placement-#: work is the repair loop's job and would break the no-drift contract.-DETAIL_KINDS = frozenset({"geometry", "detail", "material", "materials", "craftsmanship", "texture", "finish"})--#: what a detail round always does, whatever the judge said. Ordered by measured value per-#: triangle: edge treatment first (it changes how every surface reads under light), then the-#: features a viewer counts, then wear.-DEFAULT_DETAIL_LINES: tuple[str, ...] = (- "Bevel or chamfer every hard edge that a real version of this object would have "- "(2-6 mm on furniture and cast parts, 0.5-2 mm on sheet metal and small mechanisms).",- "Add the panel lines, seams and shut-lines where the real object's shells meet "- "(lids, drawers, housings, trays): 1-2 mm wide, ~1 mm deep insets.",- "Add the fasteners the real object is held together with — bolt heads, rivets, screws, "- "hinges — arrayed in a loop at the joints, sized 3-10 mm.",- "Give each material family a distinct roughness/metalness and a slightly different value; "- "no two different materials may share the same flat grey.",-)---def detail_instructions(last: Any, plan: Any, *, max_lines: int = 8) -> list[str]:- """Instruction lines for a detail round: the measured density gap first, then the- judge's detail-shaped asks, then the standing detail vocabulary; deduped and capped."""- lines: list[str] = []- seen: set[str] = set()-- def _add(text: str) -> None:- key = text.strip().lower()[:80]- if key and key not in seen:- seen.add(key)- lines.append(text.strip())-- for g in getattr(last, "gates", None) or ():- for f in getattr(g, "findings", None) or ():- if (f.data or {}).get("kind") == "under_tri_budget":- _add(f"{f.message}. {f.fix_hint}")- j = getattr(last, "judgment", None)- for item in sorted(getattr(j, "improvement_plan", None) or (),- key=lambda i: (i.priority, -getattr(i, "expected_gain", 0.0))):- if str(getattr(item, "kind", "")).lower() not in DETAIL_KINDS:- continue- target = getattr(item, "target", "") or "overall"- _add(f"{target}: {item.instruction}")- for issue in getattr(j, "issues", None) or ():- if str(getattr(issue, "kind", "")).lower() in ("material", "materials", "detail"):- _add(f"{issue.target or 'overall'}: {issue.detail}")- for text in DEFAULT_DETAIL_LINES:- _add(text)- return lines[:max_lines]diff --git a/harness/codeverse/tracks/envelope.py b/harness/codeverse/tracks/envelope.pydeleted file mode 100644index ec36c6d0..00000000--- a/harness/codeverse/tracks/envelope.py+++ /dev/null@@ -1,180 +0,0 @@-"""Single-shot envelope: parse the ``=== FILE: ... ===`` format and write files.--Split out of ``tracks/generation.py`` (kept re-exported there) to keep each-module to one responsibility. ``MultiFileParseError``/``GenerationError`` are-defined here; ``generation`` re-exports them for its callers.-"""--from __future__ import annotations--import logging-import re-from collections.abc import Callable, Collection-from pathlib import Path--from codeverse.contracts.agent import FileChange-from codeverse.workspace import Workspace--log = logging.getLogger(__name__)--ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")--SINGLE_SHOT_FORMAT = """OUTPUT FORMAT (exactly this, nothing else around it):-For EVERY file you create or fully rewrite, emit one block:--=== FILE: <relative path, e.g. src/parts/seat.js> ===-<complete file contents — the whole file, not a diff>-=== END FILE ===--Rules: paths are relative to the workspace root and must start with src/ (or public/);-emit the COMPLETE contents of each file (no "...rest unchanged"); no prose outside the blocks;-no markdown fences inside a block (plain code). Files you do not emit are left untouched."""---class GenerationError(RuntimeError):- """Raised when the generator cannot produce usable files (bad envelope, agent crash)."""---class MultiFileParseError(GenerationError):- """The single-shot answer did not contain a parseable file envelope."""---_BLOCK = re.compile(- r"^[ \t]*===\s*FILE:\s*(?P<path>[^\n=]+?)\s*===[ \t]*\r?\n(?P<body>.*?)(?:\r?\n)?^[ \t]*===\s*END FILE\s*===[ \t]*$",- re.S | re.M,-)-_FENCE = re.compile(r"```[a-zA-Z0-9_+\-]*[ \t]*(?:\r?\n)(?P<body>.*?)```", re.S)-_FENCE_PATH_HINT = re.compile(- r"(?:^|\n)[^\n]*?(?P<path>(?:src|public)/[A-Za-z0-9_./\-]+\.[a-z]{1,5})[^\n]*\n[ \t]*```", re.S-)---def parse_multifile(text: str, *, expected_files: list[str] | None = None) -> dict[str, str]:- """Parse ``SINGLE_SHOT_FORMAT`` → ``{path: content}``.-- Tolerant to: a fenced block wrapping a file body; an answer that is ONE fenced- block when exactly one entry file is expected; fenced blocks preceded by a line- naming the path. Raises ``MultiFileParseError`` otherwise.- """- files: dict[str, str] = {}- for m in _BLOCK.finditer(text):- path = _clean_path(m.group("path"))- files[path] = _strip_fence(m.group("body"))- if files:- return files- fences = list(_FENCE.finditer(text))- expected = [_clean_path(p) for p in (expected_files or [])]- if fences:- # fenced blocks preceded by a path mention- for m in fences:- probe = text[: m.start()][-400:].rstrip(" \t")- probe += ("" if probe.endswith("\n") else "\n") + "```"- hint = _FENCE_PATH_HINT.findall(probe)- if hint:- files[_clean_path(hint[-1])] = m.group("body").rstrip("\n")- if files and (not expected or set(files) <= set(expected) or len(files) == len(fences)):- return files- if len(expected) == 1:- largest = max(fences, key=lambda m: len(m.group("body")))- return {expected[0]: largest.group("body").rstrip("\n")}- if len(expected) == 1 and _looks_like_code(text):- return {expected[0]: _strip_envelope_header(text.strip("\n"))}- raise MultiFileParseError(- "no '=== FILE: <path> ===' blocks found" + (f"; expected {expected}" if expected else "")- )---_HEADER_LINE = re.compile(r"^[ \t]*===\s*FILE:\s*[^\n=]+?\s*===[ \t]*\r?\n")---def _strip_envelope_header(body: str) -> str:- """A truncated answer (cut before ``=== END FILE ===``) reaches the single-file- fallback with its ``=== FILE: … ===`` header still attached; treat the- unterminated block as the file's body instead of shipping the header as line 1."""- m = _HEADER_LINE.match(body)- return body[m.end():] if m else body---def _clean_path(p: str) -> str:- p = p.strip().strip("`'\"").replace("\\", "/")- while p.startswith("./"):- p = p[2:]- return p.lstrip("/")---def _strip_fence(body: str) -> str:- s = body.strip("\n")- m = re.fullmatch(r"```[a-zA-Z0-9_+\-]*[ \t]*\n(.*?)\n?```", s, re.S)- return (m.group(1) if m else body).rstrip("\n")---def _looks_like_code(text: str) -> bool:- t = text.strip()- return bool(t) and ("\n" in t) and not t.lower().startswith(("i ", "here", "sure", "sorry"))---def safe_relpath(path: str, allowed_roots: tuple[str, ...] = ALLOWED_ROOTS) -> str:- """Validate a model-provided relative path: inside the workspace + allowed roots."""- p = _clean_path(path)- if not p or p.startswith("/") or ".." in Path(p).parts or re.match(r"^[A-Za-z]:", p):- raise GenerationError(f"refusing to write outside the workspace: {path!r}")- if p.endswith("/"): # '=== FILE: src/parts/ ===' names a directory, not a file- raise GenerationError(f"path {path!r} is a directory, not a file")- if not any(p.startswith(root) for root in allowed_roots):- raise GenerationError(f"path {p!r} is outside the allowed roots {allowed_roots}")- return p---def write_files(- ws: Workspace,- files: dict[str, str],- *,- allowed_roots: tuple[str, ...] = ALLOWED_ROOTS,- only: Collection[str] | None = None,- on_skip: Callable[[str, str], None] | None = None,-) -> list[FileChange]:- """Write parsed files under the workspace; returns git-style FileChange rows.-- A block whose path is unsafe, outside ``allowed_roots`` (flash models love- to add README.md / package.json despite the format rule) or unwritable is- SKIPPED — reported via ``on_skip`` — instead of aborting the whole write:- the valid files were already paid for.-- ``only`` (an ``edit_only`` task's file scope, entry included when owned) skips a- path that ALREADY EXISTS and is not listed — new files stay allowed, mirroring- ``FileTools``: the single-shot envelope has no write-time gate, so this is where a- scoped task is stopped from rewriting a sibling's file."""- scope = {_clean_path(p) for p in only} if only is not None else None- changes: list[FileChange] = []- for raw, content in files.items():- try:- rel = safe_relpath(raw, allowed_roots)- except GenerationError as e:- if on_skip is not None:- on_skip(raw, str(e))- log.warning("skipping out-of-root file from generator: %s", e)- continue- dest = ws.root / rel- existed = dest.exists()- if scope is not None and existed and rel not in scope:- reason = f"out of scope: {rel} already exists and is not in this task's file list"- if on_skip is not None:- on_skip(raw, reason)- log.warning("skipping out-of-scope file from generator: %s", rel)- continue- try:- dest.parent.mkdir(parents=True, exist_ok=True)- dest.write_text(content if content.endswith("\n") else content + "\n")- except OSError as e:- # Same contract as an out-of-root path: one unwritable block (a path that- # is already a directory, a name the filesystem rejects) must not throw- # away the files that DID parse -- the whole answer was already paid for.- if on_skip is not None:- on_skip(raw, str(e))- log.warning("skipping unwritable file from generator: %s: %s", rel, e)- continue- changes.append(FileChange(path=rel, status="modified" if existed else "added",- lines_added=content.count("\n") + 1))- return changes--diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.pyindex d0660955..ff96e55f 100644--- a/harness/codeverse/tracks/generation.py+++ b/harness/codeverse/tracks/generation.py@@ -36,7 +36,8 @@ from __future__ import annotationsimport jsonimport loggingimport os-from collections.abc import Callable+import re+from collections.abc import Callable, Collectionfrom pathlib import Pathfrom typing import Any@@ -45,19 +46,174 @@ from pydantic import BaseModel, Fieldfrom codeverse.contracts.agent import AgentJob, AgentResult, FileChangefrom codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePartfrom codeverse.contracts.common import Usage-from codeverse.tracks.envelope import ( # noqa: F401 — re-exported: this was their import path- ALLOWED_ROOTS,- SINGLE_SHOT_FORMAT,- GenerationError,- MultiFileParseError,- parse_multifile,- safe_relpath,- write_files,-)from codeverse.workspace import Workspacelog = logging.getLogger(__name__)++# ===================================================================== single-shot envelope+# (merged back from codeverse/tracks/envelope.py, 2026-08-28 — the split existed only+# to hold a re-export shim; this module was its one importer)+ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")++SINGLE_SHOT_FORMAT = """OUTPUT FORMAT (exactly this, nothing else around it):+For EVERY file you create or fully rewrite, emit one block:++=== FILE: <relative path, e.g. src/parts/seat.js> ===+<complete file contents — the whole file, not a diff>+=== END FILE ===++Rules: paths are relative to the workspace root and must start with src/ (or public/);+emit the COMPLETE contents of each file (no "...rest unchanged"); no prose outside the blocks;+no markdown fences inside a block (plain code). Files you do not emit are left untouched."""+++class GenerationError(RuntimeError):+ """Raised when the generator cannot produce usable files (bad envelope, agent crash)."""+++class MultiFileParseError(GenerationError):+ """The single-shot answer did not contain a parseable file envelope."""+++_BLOCK = re.compile(+ r"^[ \t]*===\s*FILE:\s*(?P<path>[^\n=]+?)\s*===[ \t]*\r?\n(?P<body>.*?)(?:\r?\n)?^[ \t]*===\s*END FILE\s*===[ \t]*$",+ re.S | re.M,+)+_FENCE = re.compile(r"```[a-zA-Z0-9_+\-]*[ \t]*(?:\r?\n)(?P<body>.*?)```", re.S)+_FENCE_PATH_HINT = re.compile(+ r"(?:^|\n)[^\n]*?(?P<path>(?:src|public)/[A-Za-z0-9_./\-]+\.[a-z]{1,5})[^\n]*\n[ \t]*```", re.S+)+++def parse_multifile(text: str, *, expected_files: list[str] | None = None) -> dict[str, str]:+ """Parse ``SINGLE_SHOT_FORMAT`` → ``{path: content}``.++ Tolerant to: a fenced block wrapping a file body; an answer that is ONE fenced+ block when exactly one entry file is expected; fenced blocks preceded by a line+ naming the path. Raises ``MultiFileParseError`` otherwise.+ """+ files: dict[str, str] = {}+ for m in _BLOCK.finditer(text):+ path = _clean_path(m.group("path"))+ files[path] = _strip_fence(m.group("body"))+ if files:+ return files+ fences = list(_FENCE.finditer(text))+ expected = [_clean_path(p) for p in (expected_files or [])]+ if fences:+ # fenced blocks preceded by a path mention+ for m in fences:+ probe = text[: m.start()][-400:].rstrip(" \t")+ probe += ("" if probe.endswith("\n") else "\n") + "```"+ hint = _FENCE_PATH_HINT.findall(probe)+ if hint:+ files[_clean_path(hint[-1])] = m.group("body").rstrip("\n")+ if files and (not expected or set(files) <= set(expected) or len(files) == len(fences)):+ return files+ if len(expected) == 1:+ largest = max(fences, key=lambda m: len(m.group("body")))+ return {expected[0]: largest.group("body").rstrip("\n")}+ if len(expected) == 1 and _looks_like_code(text):+ return {expected[0]: _strip_envelope_header(text.strip("\n"))}+ raise MultiFileParseError(+ "no '=== FILE: <path> ===' blocks found" + (f"; expected {expected}" if expected else "")+ )+++_HEADER_LINE = re.compile(r"^[ \t]*===\s*FILE:\s*[^\n=]+?\s*===[ \t]*\r?\n")+++def _strip_envelope_header(body: str) -> str:+ """A truncated answer (cut before ``=== END FILE ===``) reaches the single-file+ fallback with its ``=== FILE: … ===`` header still attached; treat the+ unterminated block as the file's body instead of shipping the header as line 1."""+ m = _HEADER_LINE.match(body)+ return body[m.end():] if m else body+++def _clean_path(p: str) -> str:+ p = p.strip().strip("`'\"").replace("\\", "/")+ while p.startswith("./"):+ p = p[2:]+ return p.lstrip("/")+++def _strip_fence(body: str) -> str:+ s = body.strip("\n")+ m = re.fullmatch(r"```[a-zA-Z0-9_+\-]*[ \t]*\n(.*?)\n?```", s, re.S)+ return (m.group(1) if m else body).rstrip("\n")+++def _looks_like_code(text: str) -> bool:+ t = text.strip()+ return bool(t) and ("\n" in t) and not t.lower().startswith(("i ", "here", "sure", "sorry"))+++def safe_relpath(path: str, allowed_roots: tuple[str, ...] = ALLOWED_ROOTS) -> str:+ """Validate a model-provided relative path: inside the workspace + allowed roots."""+ p = _clean_path(path)+ if not p or p.startswith("/") or ".." in Path(p).parts or re.match(r"^[A-Za-z]:", p):+ raise GenerationError(f"refusing to write outside the workspace: {path!r}")+ if p.endswith("/"): # '=== FILE: src/parts/ ===' names a directory, not a file+ raise GenerationError(f"path {path!r} is a directory, not a file")+ if not any(p.startswith(root) for root in allowed_roots):+ raise GenerationError(f"path {p!r} is outside the allowed roots {allowed_roots}")+ return p+++def write_files(+ ws: Workspace,+ files: dict[str, str],+ *,+ allowed_roots: tuple[str, ...] = ALLOWED_ROOTS,+ only: Collection[str] | None = None,+ on_skip: Callable[[str, str], None] | None = None,+) -> list[FileChange]:+ """Write parsed files under the workspace; returns git-style FileChange rows.++ A block whose path is unsafe, outside ``allowed_roots`` (flash models love+ to add README.md / package.json despite the format rule) or unwritable is+ SKIPPED — reported via ``on_skip`` — instead of aborting the whole write:+ the valid files were already paid for.++ ``only`` (an ``edit_only`` task's file scope, entry included when owned) skips a+ path that ALREADY EXISTS and is not listed — new files stay allowed, mirroring+ ``FileTools``: the single-shot envelope has no write-time gate, so this is where a+ scoped task is stopped from rewriting a sibling's file."""+ scope = {_clean_path(p) for p in only} if only is not None else None+ changes: list[FileChange] = []+ for raw, content in files.items():+ try:+ rel = safe_relpath(raw, allowed_roots)+ except GenerationError as e:+ if on_skip is not None:+ on_skip(raw, str(e))+ log.warning("skipping out-of-root file from generator: %s", e)+ continue+ dest = ws.root / rel+ existed = dest.exists()+ if scope is not None and existed and rel not in scope:+ reason = f"out of scope: {rel} already exists and is not in this task's file list"+ if on_skip is not None:+ on_skip(raw, reason)+ log.warning("skipping out-of-scope file from generator: %s", rel)+ continue+ try:+ dest.parent.mkdir(parents=True, exist_ok=True)+ dest.write_text(content if content.endswith("\n") else content + "\n")+ except OSError as e:+ # Same contract as an out-of-root path: one unwritable block (a path that+ # is already a directory, a name the filesystem rejects) must not throw+ # away the files that DID parse -- the whole answer was already paid for.+ if on_skip is not None:+ on_skip(raw, str(e))+ log.warning("skipping unwritable file from generator: %s: %s", rel, e)+ continue+ changes.append(FileChange(path=rel, status="modified" if existed else "added",+ lines_added=content.count("\n") + 1))+ return changes+SINGLE_SHOT_PREFIX = "single-shot:"#: default cap on model turns per agent session: 0 = none, the session runs under the@@ -692,4 +848,4 @@ def _default_model_factory(model_id: str) -> Any:def _default_agent_factory(agent_id: str) -> Any:from codeverse.agents import get_coding_agent- return get_coding_agent(agent_id)+ return get_coding_agent(agent_id)\ No newline at end of filediff --git a/harness/codeverse/tracks/motion.py b/harness/codeverse/tracks/motion.pydeleted file mode 100644index 33ca8f07..00000000--- a/harness/codeverse/tracks/motion.py+++ /dev/null@@ -1,150 +0,0 @@-"""Planned joint motion → expected direction → deterministic check on the built URDF.--The planner writes one line per joint ("drawer pulls out towards -Y", "lid-opens upward", "door swings to the left"). When that text names an obvious-direction we map it to one of ``codeverse.spatial.joints`` direction keys-(Z-up, -Y front — the URDF/Blender authoring frame) and ask-``motion_direction_check`` whether the child link really moves that way when-the joint moves positively from rest. A wrong direction is a gate ERROR with-the concrete fix (negate the axis / swap the limits); ambiguous or silent text-is skipped — this gate never guesses.-"""--from __future__ import annotations--import logging-import time-from collections.abc import Sequence-from pathlib import Path--from codeverse.contracts.artifacts import GateFinding, GateReport, Severity-from codeverse.contracts.plan import Plan-from codeverse.conventions import to_snake-from codeverse.workspace import Workspace--log = logging.getLogger(__name__)--MOTION_GATE = "motion_direction"--#: phrase → direction key understood by ``spatial.joints.motion_direction_check``.-#: Longer phrases first so "pulls out" wins over "out"; explicit axes first of all.-_PHRASES: tuple[tuple[str, str], ...] = (- ("-y", "-y"), ("+y", "+y"), ("-z", "-z"), ("+z", "+z"), ("-x", "-x"), ("+x", "+x"),- ("towards the front", "front"), ("toward the front", "front"), ("to the front", "front"),- ("opens to the front", "front"), ("opens out", "front"), ("pulls out", "front"), ("slides out", "front"),- ("pull out", "front"), ("slide out", "front"), ("swings out", "front"), ("outward", "front"), ("forward", "front"),- ("towards the viewer", "front"), ("toward the viewer", "front"), ("frontward", "front"),- ("towards the back", "back"), ("toward the back", "back"), ("to the back", "back"), ("pushes in", "back"),- ("slides in", "back"), ("backward", "back"), ("rearward", "back"), ("inward", "back"),- ("upward", "up"), ("upwards", "up"), ("opens up", "up"), ("lifts", "up"), ("lift", "up"), ("raises", "up"),- ("raise", "up"), ("rises", "up"),- ("downward", "down"), ("downwards", "down"), ("lowers", "down"), ("drops", "down"),- ("folds down", "down"), ("opens down", "down"),- ("to the left", "left"), ("leftward", "left"), ("swings left", "left"),- ("to the right", "right"), ("rightward", "right"), ("swings right", "right"),- ("front", "front"), ("back", "back"), ("up", "up"), ("down", "down"), ("left", "left"), ("right", "right"),- ("out", "front"),-)--_SKIP_MARKERS = ("not ", "n't", "either", "both", "around", "rotates about", "spins")-_DIR_GROUPS = {"front": "y", "back": "y", "-y": "y", "+y": "y", "up": "z", "down": "z", "+z": "z", "-z": "z",- "left": "x", "right": "x", "-x": "x", "+x": "x"}---def expected_direction(motion: str) -> str | None:- """Direction key for an obvious motion description, else ``None``.-- Rules: explicit signed axes win; otherwise the first (longest) phrase hit;- text naming two different axes ("up and to the left"), negations or pure- rotations ("spins around its axis") → ``None`` (ambiguous — skip)."""- text = " ".join((motion or "").lower().replace("_", " ").split())- if not text or any(m in text for m in _SKIP_MARKERS):- return None- padded = f" {text} "- hits: list[str] = []- for phrase, key in _PHRASES:- if _contains_word(padded, phrase):- hits.append(key)- if key in ("-y", "+y", "-z", "+z", "-x", "+x"):- return key- if not hits:- return None- axes = {_DIR_GROUPS[h] for h in hits}- if len(axes) > 1:- # "opens up and out" — up/front conflict: the longest phrase decides only if one axis dominates- first_axis = _DIR_GROUPS[hits[0]]- if any(_DIR_GROUPS[h] != first_axis for h in hits[1:]):- return None- return hits[0]---def _contains_word(padded: str, phrase: str) -> bool:- """Whole-word containment (phrase boundaries are spaces or punctuation)."""- i = padded.find(phrase)- while i >= 0:- before = padded[i - 1] if i > 0 else " "- after = padded[i + len(phrase)] if i + len(phrase) < len(padded) else " "- if not before.isalnum() and not after.isalnum():- return True- i = padded.find(phrase, i + 1)- return False---def axis_fix_hint(joint_name: str, axis: Sequence[float] | None, expected: str) -> str:- if axis is not None and len(axis) == 3:- neg = tuple(-float(a) for a in axis)- return (f"in src/robot.urdf set joint '{joint_name}' <axis xyz=\"{neg[0]:g} {neg[1]:g} {neg[2]:g}\"/> "- f"(negate the axis) — or swap lower/upper so positive motion goes {expected}")- return f"negate the <axis> of joint '{joint_name}' in src/robot.urdf (or swap lower/upper) so motion goes {expected}"---def default_motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None:- """Run ``motion_direction_check`` for every plan joint with an obvious motion- direction. ``None`` when the plan has no such joints; unknown joints /- missing meshes are WARN findings (the sweep gate already reports them)."""- joints = list(getattr(plan, "joints", None) or [])- wanted = [(j, expected_direction(j.motion)) for j in joints]- wanted = [(j, d) for j, d in wanted if d is not None]- if not wanted:- return None- from codeverse.spatial import joints as sj-- urdf = _find_urdf(ws)- if urdf is None:- return None- t0 = time.time()- findings: list[GateFinding] = []- try:- robot = sj.load_urdf(urdf, ws.artifacts / "meshes")- except sj.UrdfError as e:- return GateReport(gate=MOTION_GATE, passed=True, findings=[GateFinding(- gate=MOTION_GATE, severity=Severity.WARN, target="robot.urdf", message=f"motion checks skipped: {e}")])- urdf_names = {to_snake(n): n for n in getattr(robot, "joints", {})}- for j, expected in wanted:- name = urdf_names.get(to_snake(j.name), j.name) # URDF joint named like the plan joint (any casing)- try:- chk = sj.motion_direction_check(robot, name, expected)- except sj.UrdfError as e:- findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.WARN, target=j.name,- message=f"motion check skipped: {e}", data={"expected": expected}))- continue- data = {"expected": expected, "observed_dir": list(chk.observed_dir), "motion": j.motion}- if chk.ok:- findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.INFO, target=j.name, message=chk.message, data=data))- else:- findings.append(GateFinding(- gate=MOTION_GATE, severity=Severity.ERROR, target=j.name,- message=f"{chk.message}. Plan says: \"{j.motion}\"",- fix_hint=axis_fix_hint(j.name, getattr(j, "axis", None), expected), data=data))- return GateReport(gate=MOTION_GATE, passed=not any(f.severity == Severity.ERROR for f in findings),- findings=findings, duration_ms=int((time.time() - t0) * 1000))---def _find_urdf(ws: Workspace) -> Path | None:- for cand in (ws.artifacts / "robot.urdf", ws.src / "robot.urdf"):- if cand.is_file():- return cand- return None---__all__ = ["MOTION_GATE", "axis_fix_hint", "default_motion_checks", "expected_direction"]diff --git a/harness/codeverse/tracks/reference.py b/harness/codeverse/tracks/reference.pydeleted file mode 100644index ec78b501..00000000--- a/harness/codeverse/tracks/reference.py+++ /dev/null@@ -1,112 +0,0 @@-"""Reference-image support for object tracks.--When ``spec.references`` is non-empty the planner already sees the images; the-generator prompts carry a reference note (``prompting.reference_note``) and, for-single-shot, the images themselves; the main judge becomes ``ReferenceJudge``-(rubric ``reference_v1``). This module adds the deterministic part:--* ``silhouette_gate`` — after rendering, the front view's outline IoU against- the *target* reference (``spatial.silhouette.compare_silhouette``) becomes a- ``reference_silhouette`` gate finding (WARN, with the numbers in ``data``).-* ``reference_refine_tasks`` — when that IoU is below ``IOU_REFINE_THRESHOLD``- the next refine round gets a priority-1 task saying so, with the numbers.-"""--from __future__ import annotations--import logging-from pathlib import Path--from codeverse.contracts.artifacts import GateFinding, GateReport, RenderSet, RenderView, Severity-from codeverse.contracts.run import RoundRecord-from codeverse.orchestrator.rounds import RefineTask-from codeverse.tracks.common import RunContext--log = logging.getLogger(__name__)--SILHOUETTE_GATE = "reference_silhouette"-IOU_REFINE_THRESHOLD = 0.6-FRONT_VIEW_NAMES: tuple[str, ...] = ("front", "front_right_34", "front_left_34")---def target_reference(ctx: RunContext) -> str | None:- """Path of the reference image to match the silhouette against (role ``target`` first)."""- refs = [r for r in ctx.spec.references if Path(r.path).is_file()]- if not refs:- return None- return next((r.path for r in refs if r.role == "target"), refs[0].path)---def front_view(renders: RenderSet) -> RenderView | None:- for name in FRONT_VIEW_NAMES:- for v in renders.views:- if v.name == name:- return v- return renders.views[0] if renders.views else None---def silhouette_gate(ctx: RunContext, renders: RenderSet) -> GateReport | None:- """``None`` when the spec has no reference images or nothing could be compared."""- ref = target_reference(ctx)- view = front_view(renders)- if ref is None or view is None:- return None- try:- res = ctx.services.silhouette(view.path, ref)- except Exception as e: # noqa: BLE001 — advisory measurement; never fails a round- log.warning("compare_silhouette failed: %s", e)- return GateReport(gate=SILHOUETTE_GATE, passed=True, findings=[GateFinding(- gate=SILHOUETTE_GATE, severity=Severity.INFO, target="overall", message=f"silhouette comparison unavailable: {e}")])- iou = float(res.get("iou", 0.0)) if isinstance(res, dict) else 0.0- reliable = bool(res.get("reliable", True)) if isinstance(res, dict) else False- data = {k: v for k, v in (res.items() if isinstance(res, dict) else []) if isinstance(v, (int, float, str, bool))}- data["view"] = view.name- data["reference"] = ref- low = reliable and iou < IOU_REFINE_THRESHOLD- msg = (f"front-view outline IoU vs reference = {iou:.3f}" + ("" if reliable else " (unreliable mask)")- + (f" — below {IOU_REFINE_THRESHOLD:.1f}" if low else ""))- finding = GateFinding(gate=SILHOUETTE_GATE, severity=Severity.WARN if low else Severity.INFO, target="overall",- message=msg, data=data,- fix_hint=("match the reference outline: compare proportions (aspect ratio), overall extents and the "- "silhouette of each major part against the reference image" if low else ""))- return GateReport(gate=SILHOUETTE_GATE, passed=True, findings=[finding])---def silhouette_iou(rec: RoundRecord) -> tuple[float, dict] | None:- """(iou, data) recorded by ``silhouette_gate`` in a round, if any."""- for g in rec.gates:- if g.gate != SILHOUETTE_GATE:- continue- for f in g.findings:- if "iou" in f.data:- try:- return float(f.data["iou"]), dict(f.data)- except (TypeError, ValueError):- return None- return None---def reference_refine_tasks(ctx: RunContext, last: RoundRecord) -> list[RefineTask]:- """A priority-1 refine task when the last round's silhouette IoU was below threshold."""- if not ctx.spec.references:- return []- hit = silhouette_iou(last)- if hit is None:- return []- iou, data = hit- if iou >= IOU_REFINE_THRESHOLD or data.get("reliable") is False:- return []- bits = [f"Front-view silhouette IoU vs the reference image is {iou:.2f} (target ≥ {IOU_REFINE_THRESHOLD:.1f})."]- aspect = data.get("aspect_ratio_err")- if isinstance(aspect, (int, float)):- ra, rr = data.get("ref_aspect"), data.get("render_aspect")- if isinstance(ra, (int, float)) and isinstance(rr, (int, float)):- bits.append(f"Aspect (w/h): reference {ra:.2f} vs model {rr:.2f} — " +- ("make the object wider relative to its height" if rr < ra else "make the object taller relative to its width") + ".")- bits.append("Re-read the reference: match the outline of every major part (overall proportions first, then part shapes), "- "keeping names and the plan's dimensions unless the reference clearly disagrees.")- return [RefineTask(target="overall", kind="reference", instruction=" ".join(bits), priority=1, source="gate")]---__all__ = ["FRONT_VIEW_NAMES", "IOU_REFINE_THRESHOLD", "SILHOUETTE_GATE", "front_view", "reference_refine_tasks",- "silhouette_gate", "silhouette_iou", "target_reference"]diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.pyindex c5958b6e..1db478be 100644--- a/harness/codeverse/tracks/scene.py+++ b/harness/codeverse/tracks/scene.py@@ -59,12 +59,13 @@ from codeverse.tracks.prompting import (reference_images,)from codeverse.tracks.repair import format_error_report-from codeverse.tracks.scene_asset_gen import select_assets, single_shot_ctxfrom codeverse.tracks.scene_assets import (MAX_ASSETS,AssetResult,asset_api_summary,run_asset_stage,+ select_assets,+ single_shot_ctx,)from codeverse.workspace import Workspacediff --git a/harness/codeverse/tracks/scene_asset_gen.py b/harness/codeverse/tracks/scene_asset_gen.pydeleted file mode 100644index da940522..00000000--- a/harness/codeverse/tracks/scene_asset_gen.py+++ /dev/null@@ -1,331 +0,0 @@-"""Cheap scene-asset generation: single-shot first, deterministic check, dedupe.--Measured on the 2026-08-23 scene battery: every asset was a full coding-agent-session (26–44 turns, 3–4 whole-scene ``build`` + ``scene_probe`` calls each) —-$0.11–0.25 and 1–8 minutes **per asset file**, 45 % of the whole run's cost. An-asset module is one self-contained file; it does not need a tool loop.--So the default here is:--1. **single-shot** the file (one chat call), then-2. run a deterministic node check (import the module, call the builder, inspect- the returned group: exports, NaN vertices, empty bbox, triangle budget) —- ~0.08 s, no browser, precise error text with line numbers, then-3. **one** error-feedback single-shot repair, then-4. only if that still fails: escalate to a real agent session.--``blender_glb`` assets are heroes and keep their agent session.-``select_assets`` caps the list by plan priority and, only when the plan is over-that cap, folds near-identical props (two rock variants) into ONE factory that-zones call with an ``opts.variant`` — a rescue for props truncation would drop.-"""--from __future__ import annotations--import logging-from dataclasses import replace-from pathlib import Path--from pydantic import BaseModel, Field--from codeverse.contracts.plan import AssetPlan-from codeverse.conventions import to_pascal, to_snake-from codeverse.proc import write_json_atomic, write_text_atomic-from codeverse.tracks.common import RunContext-from codeverse.tracks.generation import SINGLE_SHOT_PREFIX, is_single_shot-from codeverse.workspace import Workspace--log = logging.getLogger(__name__)--#: max triangles for ONE asset instance (the scene contract's budget)-ASSET_MAX_TRIS = 15_000---# ----------------------------------------------------------------------------- strategy-def single_shot_agent_id(agent_id: str, chat_model_id: str = "") -> str:- """The single-shot strategy id for this run, or "" when there is no chat model.-- Single-shot is ONE api call that returns the asset file — the cheap path the asset- stage tries before escalating to a full agent session. It needs a chat model, and- the coding agent is always a vendor CLI (which exposes none), so the model comes- from ``chat_model_id`` — the run's planner backend, which is always an API model.- Until 2026-08-28 it was derived from the in-process ``api-agent`` generator id;- that backend is gone."""- if is_single_shot(agent_id):- return agent_id- # a SHAPE check only, deliberately not models.registry.parse_model_id: whether the- # id resolves is the SERVICES' call (tests run fake providers like "fake:planner"),- # and single_shot_ctx already degrades to the agent path when chat_model() raises- return SINGLE_SHOT_PREFIX + chat_model_id if ":" in chat_model_id else ""---def single_shot_ctx(ctx: RunContext) -> RunContext | None:- """A copy of ``ctx`` bound to the single-shot strategy, or None when the- generator has no usable chat model (CLI agents, tests with fake services)."""- cached = ctx.extra.get("_single_shot_ctx")- if cached is not None:- return cached or None # False = known-unavailable- sid = single_shot_agent_id(ctx.agent_id, ctx.spec.backends.planner)- sub: RunContext | None = None- if sid:- try:- model = ctx.model if is_single_shot(ctx.agent_id) else ctx.services.chat_model(sid[len(SINGLE_SHOT_PREFIX):])- except Exception as e: # noqa: BLE001 — no chat model → keep the agent path- log.info("single-shot generation unavailable for %s: %s", ctx.agent_id, e)- model = None- if model is not None:- sub = replace(ctx, agent_id=sid, model=model, agent=None)- ctx.extra["_single_shot_ctx"] = sub or False- return sub---# ----------------------------------------------------------------------------- deterministic check-class AssetCheck(BaseModel):- """Result of importing the asset module and calling its builder."""-- ok: bool = False- ran: bool = Field(default=False, description="False = the checker itself could not run (node missing)")- fatal: bool = Field(default=False, description="the module does not import / build at all — zones must not use it")- errors: list[str] = Field(default_factory=list)- warnings: list[str] = Field(default_factory=list)- size_m: tuple[float, float, float] | None = None- min_y: float | None = None- tris: int = 0- meshes: int = 0- materials: int = 0-- def report(self, limit: int = 6) -> str:- return "\n".join(f"- {e}" for e in (self.errors + self.warnings)[:limit])---_CHECK_JS = r"""-import * as THREE from 'three';-const [, , fileUrl, exportName] = process.argv;-const out = { ok: false, errors: [], warnings: [], size_m: null, tris: 0, meshes: 0, materials: 0 };-try {- const mod = await import(fileUrl);- const fn = mod[exportName] ?? mod.default;- if (typeof fn !== 'function') {- out.errors.push(`missing export: this file must \`export function ${exportName}(THREE, opts = {})\` (found: ${Object.keys(mod).join(', ') || 'nothing'})`);- } else {- const g = fn(THREE, {});- if (!g || !g.isObject3D) {- out.errors.push(`${exportName}(THREE) must return a THREE.Group / Object3D (got ${Object.prototype.toString.call(g)})`);- } else {- const box = new THREE.Box3().setFromObject(g);- const mats = new Set();- let bad = 0;- g.traverse((o) => {- if (!o.isMesh) return;- out.meshes += 1;- mats.add(o.material?.uuid ?? o.material);- const pos = o.geometry?.attributes?.position;- if (!pos) return;- const arr = pos.array;- for (let i = 0; i < arr.length; i++) if (!Number.isFinite(arr[i])) { bad += 1; break; }- const idx = o.geometry.index;- out.tris += ((idx ? idx.count : pos.count) / 3) * (o.isInstancedMesh ? o.count : 1);- });- out.materials = mats.size;- if (bad) out.errors.push(`${bad} mesh(es) have NaN/Infinity vertex positions`);- if (out.meshes === 0) out.errors.push('the returned group contains no meshes');- if (box.isEmpty()) out.errors.push('the returned group has an empty bounding box');- else {- const s = new THREE.Vector3(); box.getSize(s);- if (!Number.isFinite(s.x + s.y + s.z)) out.errors.push('the bounding box is not finite');- else { out.size_m = [+s.x.toFixed(3), +s.y.toFixed(3), +s.z.toFixed(3)]; out.min_y = +box.min.y.toFixed(3); }- }- out.tris = Math.round(out.tris);- }- }-} catch (e) {- out.errors.push(`${e?.name || 'Error'}: ${e?.message || String(e)}`);- const stack = String(e?.stack || '').split('\n').slice(1, 4).filter((l) => l.includes(fileUrl.replace('file://', '')));- if (stack.length) out.errors.push('at ' + stack.map((l) => l.trim()).join(' / '));-}-out.ok = out.errors.length === 0;-console.log(JSON.stringify(out));-"""---def _checker_path(ctx: RunContext) -> Path:- """The checker script lives in the harness cache, never in the workspace."""- p = Path(ctx.settings.cache_dir) / "scene_asset_check.mjs"- if not p.is_file() or p.read_text() != _CHECK_JS:- # run_asset_stage fans the assets out over a thread pool, so every thread- # used to write the SAME '<cache>/scene_asset_check.mjs.tmp' and the loser's- # replace() raised FileNotFoundError -- swallowed below into ok=True, ran=False.- write_text_atomic(p, _CHECK_JS)- return p---def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: float = 60.0,- expected_size_m: tuple[float, float, float] | None = None) -> AssetCheck:- """Import ``rel`` in node, call ``build<Pascal>(THREE, {})`` and inspect the group.-- Never raises: an unavailable node runtime yields ``ran=False, ok=True`` so the- strategy falls back to "the scene build will catch it"."""- path = ctx.ws.root / rel- if not path.is_file():- return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])- try:- from codeverse.spatial.node import run_node-- res = run_node(_checker_path(ctx), [path.resolve().as_uri(), f"build{pascal}"], cwd=ctx.ws.root,- three_hook=True, timeout_s=timeout_s, check=False)- data = res.last_json- if data is None:- tail = (res.stderr or res.stdout or "").strip().splitlines()[-3:]- return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"the module failed to load: {' / '.join(tail)[:300]}"])- chk = AssetCheck(ok=bool(data.get("ok")), ran=True, errors=list(data.get("errors") or []),- warnings=list(data.get("warnings") or []),- size_m=tuple(data["size_m"]) if data.get("size_m") else None, # type: ignore[arg-type]- min_y=data.get("min_y"), tris=int(data.get("tris") or 0),- meshes=int(data.get("meshes") or 0), materials=int(data.get("materials") or 0))- except Exception as e: # noqa: BLE001 — the checker is an optimisation, never a blocker- log.warning("asset check could not run for %s: %s", rel, e)- return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {type(e).__name__}"])- chk.fatal = not chk.ok # everything the JS side reports is a hard failure to import/build- _soft_findings(chk, expected_size_m) # …the rest is wrong-but-usable: worth a repair, not a veto- return chk---def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None) -> None:- """Findings that make the asset WRONG but not broken → errors worth one repair."""- if not chk.ok:- return- if chk.min_y is not None and chk.min_y < -0.02:- chk.errors.append(f"the group sinks {abs(chk.min_y):.2f} m below y=0 — its lowest point must sit at y=0")- if chk.tris > ASSET_MAX_TRIS:- chk.errors.append(f"{chk.tris} triangles exceeds the {ASSET_MAX_TRIS} budget per asset — lower the segment counts")- if chk.meshes == 1 and chk.materials <= 1 and chk.tris < 200:- chk.errors.append("the asset is still a single low-poly box (one mesh, one material): build it from several "- "parts with distinct materials so it reads as the described object")- if expected and chk.size_m:- for axis, got, want in zip("whd", chk.size_m, expected, strict=False):- if want > 0.05 and (got > want * 2.5 or got < want * 0.4):- chk.errors.append(f"measured {axis}={got:.2f} m but the plan says {want:.2f} m — rescale to the planned size (±5 %)")- break- chk.ok = not chk.errors---def repair_feedback(chk: AssetCheck, rel: str) -> str:- """The error-feedback block for the ONE single-shot repair attempt."""- return (f"## The file you wrote did NOT pass the deterministic asset check\n"- f"The harness imported `{rel}` in node and called its builder. Fix exactly these, "- f"return the COMPLETE file again:\n{chk.report()}\n")---# ----------------------------------------------------------------------------- dedupe-#: head noun → canonical family (near-identical scene props collapse into one factory)-_FAMILY = {- "rock": "rock", "boulder": "rock", "stone": "rock", "pebble": "rock", "rubble": "rock", "cobble": "rock",- "tree": "tree", "sapling": "tree", "pine": "tree", "conifer": "tree", "palm": "tree",- "bush": "bush", "shrub": "bush", "hedge": "bush", "scrub": "bush", "fern": "bush", "grass": "bush",- "planter": "planter", "pot": "planter", "urn": "planter", "trough": "planter", "tub": "planter",- "lamp": "lamp", "lantern": "lamp", "light": "lamp", "lightpost": "lamp", "sconce": "lamp",- "bench": "bench", "seat": "bench", "stool": "bench", "chair": "bench",- "crate": "crate", "box": "crate", "carton": "crate", "barrel": "crate",- "post": "post", "pole": "post", "pillar": "post", "column": "post", "bollard": "post", "stake": "post",- "fence": "fence", "railing": "fence", "rail": "fence", "balustrade": "fence",- "table": "table", "desk": "table",-}---def _family(name: str) -> str:- head = to_snake(name).split("_")[-1].rstrip("s") or to_snake(name)- return _FAMILY.get(head, head)---def select_assets(assets: list[AssetPlan], cap: int) -> tuple[list[AssetPlan], dict[str, str]]:- """The assets to actually build, in plan (= priority) order, plus the merge map.-- Dedupe is a *rescue*, not a default: while the plan fits under ``cap`` every planned- prop is built (single-shot assets are nearly free, and a distinct prop is worth more- than a variant flag). Only an over-long list is folded — turning "drop the 9th- asset" into "the 9th asset is a variant of the 3rd" — and whatever is still over the- cap is truncated by priority."""- alias: dict[str, str] = {}- if len(assets) > cap:- assets, alias = dedupe_assets(assets)- if len(assets) > cap:- kept = {a.name for a in assets[:cap]}- assets = assets[:cap]- alias = {k: v for k, v in alias.items() if v in kept}- return assets, alias---def dedupe_assets(assets: list[AssetPlan]) -> tuple[list[AssetPlan], dict[str, str]]:- """Fold near-identical props into ONE parameterised factory.-- Two assets merge when their head nouns belong to the same family AND their- largest dimensions are within 3× — "HeroBoulder" (2.5 m) and "TalusRock"- (0.5 m) are different props; "SteppingStone" and "PondRock" are one factory- with a variant. Plan order is priority: the first one survives.- Returns ``(kept_assets, {dropped_name: kept_name})``."""- kept: list[AssetPlan] = []- alias: dict[str, str] = {}- for a in assets:- fam = _family(a.name)- twin = next((k for k in kept if k.kind == a.kind and _family(k.name) == fam- and _ratio(max(k.approx_size_m), max(a.approx_size_m)) <= 3.0), None)- if twin is None:- kept.append(a)- continue- alias[a.name] = twin.name- if alias:- kept = [_with_variants(k, [n for n, t in alias.items() if t == k.name],- {n: a for n, a in ((x.name, x) for x in assets)}) for k in kept]- return kept, alias---def _ratio(a: float, b: float) -> float:- lo, hi = sorted((abs(a) or 1e-6, abs(b) or 1e-6))- return hi / lo---def _with_variants(asset: AssetPlan, dropped: list[str], by_name: dict[str, AssetPlan]) -> AssetPlan:- """Tell the kept asset it must also serve as its merged twins (opts.variant)."""- if not dropped:- return asset- lines = [f"variant {i + 1} = {n} ({by_name[n].description.strip()})" for i, n in enumerate(dropped) if n in by_name]- extra = (f" This ONE factory must also cover: {'; '.join(lines)}. Read `opts.variant` (integer, 0 = the base "- f"asset above, 1..{len(lines)} = the variants in that order) and `opts.scale` (number, default 1) and "- f"change proportions/detail/colour accordingly — zone code calls the same builder with different opts.")- return asset.model_copy(update={"description": asset.description.rstrip() + extra})---def variant_index(alias: dict[str, str], name: str) -> int:- """1-based variant index of a merged asset within its surviving factory."""- kept = alias.get(name)- if not kept:- return 0- return sorted(n for n, t in alias.items() if t == kept).index(name) + 1---def write_dedupe_note(ws: Workspace, alias: dict[str, str]) -> None:- """Persist the merge map next to the other stage artifacts (flywheel + debugging)."""- if alias:- write_json_atomic(ws.root / "stages" / "asset_aliases.json", {"alias": alias})---def write_variant_shims(ws: Workspace, alias: dict[str, str], available: set[str]) -> list[str]:- """Replace a merged asset's skeleton stub with a shim onto the surviving factory.-- Zone code is TOLD to call ``build<Kept>(THREE, {variant: n})``, but a zone that- imports the old name anyway must get the real prop, not the placeholder blockout- box the skeleton left behind."""- written: list[str] = []- for dropped, kept in sorted(alias.items()):- if kept not in available:- continue- rel = f"src/assets/{to_snake(dropped)}.js"- path = ws.root / rel- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(- f"// {dropped} is a variant of {kept} (assets were merged into one factory).\n"- f"import {{ build{to_pascal(kept)} }} from './{to_snake(kept)}.js';\n\n"- f"export function build{to_pascal(dropped)}(THREE, opts = {{}}) {{\n"- f" return build{to_pascal(kept)}(THREE, {{ variant: {variant_index(alias, dropped)}, ...opts }});\n}}\n")- written.append(rel)- return writtendiff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.pyindex a879eb66..20802aa8 100644--- a/harness/codeverse/tracks/scene_assets.py+++ b/harness/codeverse/tracks/scene_assets.py@@ -31,21 +31,12 @@ from codeverse.contracts.plan import AssetPlan, BBox, PartPlan, ScenePlan, Statifrom codeverse.contracts.spec import Specfrom codeverse.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snakefrom codeverse.fanout import fan_out+from codeverse.proc import write_json_atomic, write_text_atomicfrom codeverse.prompts import renderfrom codeverse.tracks.common import RunContext, language_contract, load_prompt_or-from codeverse.tracks.generation import GenerationTask, generate+from codeverse.tracks.generation import SINGLE_SHOT_PREFIX, GenerationTask, generate, is_single_shotfrom codeverse.tracks.prompting import base_prompt_contextfrom codeverse.tracks.repair import build_with_repair-from codeverse.tracks.scene_asset_gen import (- AssetCheck,- check_threejs_asset,- repair_feedback,- select_assets,- single_shot_ctx,- variant_index,- write_dedupe_note,- write_variant_shims,-)from codeverse.workspace import Workspacelog = logging.getLogger(__name__)@@ -422,3 +413,299 @@ def _read(ws: Workspace, rel: str, limit: int = 30_000) -> str:p = ws.root / relreturn p.read_text(errors="replace")[:limit] if p.is_file() else ""++# ===================================================================== cheap asset generation+# (merged from codeverse/tracks/scene_asset_gen.py, 2026-08-28 — single-shot + check ++# dedupe were only ever called from this stage and from scene.py)+#: max triangles for ONE asset instance (the scene contract's budget)+ASSET_MAX_TRIS = 15_000+++# ----------------------------------------------------------------------------- strategy+def single_shot_agent_id(agent_id: str, chat_model_id: str = "") -> str:+ """The single-shot strategy id for this run, or "" when there is no chat model.++ Single-shot is ONE api call that returns the asset file — the cheap path the asset+ stage tries before escalating to a full agent session. It needs a chat model, and+ the coding agent is always a vendor CLI (which exposes none), so the model comes+ from ``chat_model_id`` — the run's planner backend, which is always an API model.+ Until 2026-08-28 it was derived from the in-process ``api-agent`` generator id;+ that backend is gone."""+ if is_single_shot(agent_id):+ return agent_id+ # a SHAPE check only, deliberately not models.registry.parse_model_id: whether the+ # id resolves is the SERVICES' call (tests run fake providers like "fake:planner"),+ # and single_shot_ctx already degrades to the agent path when chat_model() raises+ return SINGLE_SHOT_PREFIX + chat_model_id if ":" in chat_model_id else ""+++def single_shot_ctx(ctx: RunContext) -> RunContext | None:+ """A copy of ``ctx`` bound to the single-shot strategy, or None when the+ generator has no usable chat model (CLI agents, tests with fake services)."""+ cached = ctx.extra.get("_single_shot_ctx")+ if cached is not None:+ return cached or None # False = known-unavailable+ sid = single_shot_agent_id(ctx.agent_id, ctx.spec.backends.planner)+ sub: RunContext | None = None+ if sid:+ try:+ model = ctx.model if is_single_shot(ctx.agent_id) else ctx.services.chat_model(sid[len(SINGLE_SHOT_PREFIX):])+ except Exception as e: # noqa: BLE001 — no chat model → keep the agent path+ log.info("single-shot generation unavailable for %s: %s", ctx.agent_id, e)+ model = None+ if model is not None:+ sub = replace(ctx, agent_id=sid, model=model, agent=None)+ ctx.extra["_single_shot_ctx"] = sub or False+ return sub+++# ----------------------------------------------------------------------------- deterministic check+class AssetCheck(BaseModel):+ """Result of importing the asset module and calling its builder."""++ ok: bool = False+ ran: bool = Field(default=False, description="False = the checker itself could not run (node missing)")+ fatal: bool = Field(default=False, description="the module does not import / build at all — zones must not use it")+ errors: list[str] = Field(default_factory=list)+ warnings: list[str] = Field(default_factory=list)+ size_m: tuple[float, float, float] | None = None+ min_y: float | None = None+ tris: int = 0+ meshes: int = 0+ materials: int = 0++ def report(self, limit: int = 6) -> str:+ return "\n".join(f"- {e}" for e in (self.errors + self.warnings)[:limit])+++_CHECK_JS = r"""+import * as THREE from 'three';+const [, , fileUrl, exportName] = process.argv;+const out = { ok: false, errors: [], warnings: [], size_m: null, tris: 0, meshes: 0, materials: 0 };+try {+ const mod = await import(fileUrl);+ const fn = mod[exportName] ?? mod.default;+ if (typeof fn !== 'function') {+ out.errors.push(`missing export: this file must \`export function ${exportName}(THREE, opts = {})\` (found: ${Object.keys(mod).join(', ') || 'nothing'})`);+ } else {+ const g = fn(THREE, {});+ if (!g || !g.isObject3D) {+ out.errors.push(`${exportName}(THREE) must return a THREE.Group / Object3D (got ${Object.prototype.toString.call(g)})`);+ } else {+ const box = new THREE.Box3().setFromObject(g);+ const mats = new Set();+ let bad = 0;+ g.traverse((o) => {+ if (!o.isMesh) return;+ out.meshes += 1;+ mats.add(o.material?.uuid ?? o.material);+ const pos = o.geometry?.attributes?.position;+ if (!pos) return;+ const arr = pos.array;+ for (let i = 0; i < arr.length; i++) if (!Number.isFinite(arr[i])) { bad += 1; break; }+ const idx = o.geometry.index;+ out.tris += ((idx ? idx.count : pos.count) / 3) * (o.isInstancedMesh ? o.count : 1);+ });+ out.materials = mats.size;+ if (bad) out.errors.push(`${bad} mesh(es) have NaN/Infinity vertex positions`);+ if (out.meshes === 0) out.errors.push('the returned group contains no meshes');+ if (box.isEmpty()) out.errors.push('the returned group has an empty bounding box');+ else {+ const s = new THREE.Vector3(); box.getSize(s);+ if (!Number.isFinite(s.x + s.y + s.z)) out.errors.push('the bounding box is not finite');+ else { out.size_m = [+s.x.toFixed(3), +s.y.toFixed(3), +s.z.toFixed(3)]; out.min_y = +box.min.y.toFixed(3); }+ }+ out.tris = Math.round(out.tris);+ }+ }+} catch (e) {+ out.errors.push(`${e?.name || 'Error'}: ${e?.message || String(e)}`);+ const stack = String(e?.stack || '').split('\n').slice(1, 4).filter((l) => l.includes(fileUrl.replace('file://', '')));+ if (stack.length) out.errors.push('at ' + stack.map((l) => l.trim()).join(' / '));+}+out.ok = out.errors.length === 0;+console.log(JSON.stringify(out));+"""+++def _checker_path(ctx: RunContext) -> Path:+ """The checker script lives in the harness cache, never in the workspace."""+ p = Path(ctx.settings.cache_dir) / "scene_asset_check.mjs"+ if not p.is_file() or p.read_text() != _CHECK_JS:+ # run_asset_stage fans the assets out over a thread pool, so every thread+ # used to write the SAME '<cache>/scene_asset_check.mjs.tmp' and the loser's+ # replace() raised FileNotFoundError -- swallowed below into ok=True, ran=False.+ write_text_atomic(p, _CHECK_JS)+ return p+++def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: float = 60.0,+ expected_size_m: tuple[float, float, float] | None = None) -> AssetCheck:+ """Import ``rel`` in node, call ``build<Pascal>(THREE, {})`` and inspect the group.++ Never raises: an unavailable node runtime yields ``ran=False, ok=True`` so the+ strategy falls back to "the scene build will catch it"."""+ path = ctx.ws.root / rel+ if not path.is_file():+ return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])+ try:+ from codeverse.spatial.node import run_node++ res = run_node(_checker_path(ctx), [path.resolve().as_uri(), f"build{pascal}"], cwd=ctx.ws.root,+ three_hook=True, timeout_s=timeout_s, check=False)+ data = res.last_json+ if data is None:+ tail = (res.stderr or res.stdout or "").strip().splitlines()[-3:]+ return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"the module failed to load: {' / '.join(tail)[:300]}"])+ chk = AssetCheck(ok=bool(data.get("ok")), ran=True, errors=list(data.get("errors") or []),+ warnings=list(data.get("warnings") or []),+ size_m=tuple(data["size_m"]) if data.get("size_m") else None, # type: ignore[arg-type]+ min_y=data.get("min_y"), tris=int(data.get("tris") or 0),+ meshes=int(data.get("meshes") or 0), materials=int(data.get("materials") or 0))+ except Exception as e: # noqa: BLE001 — the checker is an optimisation, never a blocker+ log.warning("asset check could not run for %s: %s", rel, e)+ return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {type(e).__name__}"])+ chk.fatal = not chk.ok # everything the JS side reports is a hard failure to import/build+ _soft_findings(chk, expected_size_m) # …the rest is wrong-but-usable: worth a repair, not a veto+ return chk+++def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None) -> None:+ """Findings that make the asset WRONG but not broken → errors worth one repair."""+ if not chk.ok:+ return+ if chk.min_y is not None and chk.min_y < -0.02:+ chk.errors.append(f"the group sinks {abs(chk.min_y):.2f} m below y=0 — its lowest point must sit at y=0")+ if chk.tris > ASSET_MAX_TRIS:+ chk.errors.append(f"{chk.tris} triangles exceeds the {ASSET_MAX_TRIS} budget per asset — lower the segment counts")+ if chk.meshes == 1 and chk.materials <= 1 and chk.tris < 200:+ chk.errors.append("the asset is still a single low-poly box (one mesh, one material): build it from several "+ "parts with distinct materials so it reads as the described object")+ if expected and chk.size_m:+ for axis, got, want in zip("whd", chk.size_m, expected, strict=False):+ if want > 0.05 and (got > want * 2.5 or got < want * 0.4):+ chk.errors.append(f"measured {axis}={got:.2f} m but the plan says {want:.2f} m — rescale to the planned size (±5 %)")+ break+ chk.ok = not chk.errors+++def repair_feedback(chk: AssetCheck, rel: str) -> str:+ """The error-feedback block for the ONE single-shot repair attempt."""+ return (f"## The file you wrote did NOT pass the deterministic asset check\n"+ f"The harness imported `{rel}` in node and called its builder. Fix exactly these, "+ f"return the COMPLETE file again:\n{chk.report()}\n")+++# ----------------------------------------------------------------------------- dedupe+#: head noun → canonical family (near-identical scene props collapse into one factory)+_FAMILY = {+ "rock": "rock", "boulder": "rock", "stone": "rock", "pebble": "rock", "rubble": "rock", "cobble": "rock",+ "tree": "tree", "sapling": "tree", "pine": "tree", "conifer": "tree", "palm": "tree",+ "bush": "bush", "shrub": "bush", "hedge": "bush", "scrub": "bush", "fern": "bush", "grass": "bush",+ "planter": "planter", "pot": "planter", "urn": "planter", "trough": "planter", "tub": "planter",+ "lamp": "lamp", "lantern": "lamp", "light": "lamp", "lightpost": "lamp", "sconce": "lamp",+ "bench": "bench", "seat": "bench", "stool": "bench", "chair": "bench",+ "crate": "crate", "box": "crate", "carton": "crate", "barrel": "crate",+ "post": "post", "pole": "post", "pillar": "post", "column": "post", "bollard": "post", "stake": "post",+ "fence": "fence", "railing": "fence", "rail": "fence", "balustrade": "fence",+ "table": "table", "desk": "table",+}+++def _family(name: str) -> str:+ head = to_snake(name).split("_")[-1].rstrip("s") or to_snake(name)+ return _FAMILY.get(head, head)+++def select_assets(assets: list[AssetPlan], cap: int) -> tuple[list[AssetPlan], dict[str, str]]:+ """The assets to actually build, in plan (= priority) order, plus the merge map.++ Dedupe is a *rescue*, not a default: while the plan fits under ``cap`` every planned+ prop is built (single-shot assets are nearly free, and a distinct prop is worth more+ than a variant flag). Only an over-long list is folded — turning "drop the 9th+ asset" into "the 9th asset is a variant of the 3rd" — and whatever is still over the+ cap is truncated by priority."""+ alias: dict[str, str] = {}+ if len(assets) > cap:+ assets, alias = dedupe_assets(assets)+ if len(assets) > cap:+ kept = {a.name for a in assets[:cap]}+ assets = assets[:cap]+ alias = {k: v for k, v in alias.items() if v in kept}+ return assets, alias+++def dedupe_assets(assets: list[AssetPlan]) -> tuple[list[AssetPlan], dict[str, str]]:+ """Fold near-identical props into ONE parameterised factory.++ Two assets merge when their head nouns belong to the same family AND their+ largest dimensions are within 3× — "HeroBoulder" (2.5 m) and "TalusRock"+ (0.5 m) are different props; "SteppingStone" and "PondRock" are one factory+ with a variant. Plan order is priority: the first one survives.+ Returns ``(kept_assets, {dropped_name: kept_name})``."""+ kept: list[AssetPlan] = []+ alias: dict[str, str] = {}+ for a in assets:+ fam = _family(a.name)+ twin = next((k for k in kept if k.kind == a.kind and _family(k.name) == fam+ and _ratio(max(k.approx_size_m), max(a.approx_size_m)) <= 3.0), None)+ if twin is None:+ kept.append(a)+ continue+ alias[a.name] = twin.name+ if alias:+ kept = [_with_variants(k, [n for n, t in alias.items() if t == k.name],+ {n: a for n, a in ((x.name, x) for x in assets)}) for k in kept]+ return kept, alias+++def _ratio(a: float, b: float) -> float:+ lo, hi = sorted((abs(a) or 1e-6, abs(b) or 1e-6))+ return hi / lo+++def _with_variants(asset: AssetPlan, dropped: list[str], by_name: dict[str, AssetPlan]) -> AssetPlan:+ """Tell the kept asset it must also serve as its merged twins (opts.variant)."""+ if not dropped:+ return asset+ lines = [f"variant {i + 1} = {n} ({by_name[n].description.strip()})" for i, n in enumerate(dropped) if n in by_name]+ extra = (f" This ONE factory must also cover: {'; '.join(lines)}. Read `opts.variant` (integer, 0 = the base "+ f"asset above, 1..{len(lines)} = the variants in that order) and `opts.scale` (number, default 1) and "+ f"change proportions/detail/colour accordingly — zone code calls the same builder with different opts.")+ return asset.model_copy(update={"description": asset.description.rstrip() + extra})+++def variant_index(alias: dict[str, str], name: str) -> int:+ """1-based variant index of a merged asset within its surviving factory."""+ kept = alias.get(name)+ if not kept:+ return 0+ return sorted(n for n, t in alias.items() if t == kept).index(name) + 1+++def write_dedupe_note(ws: Workspace, alias: dict[str, str]) -> None:+ """Persist the merge map next to the other stage artifacts (flywheel + debugging)."""+ if alias:+ write_json_atomic(ws.root / "stages" / "asset_aliases.json", {"alias": alias})+++def write_variant_shims(ws: Workspace, alias: dict[str, str], available: set[str]) -> list[str]:+ """Replace a merged asset's skeleton stub with a shim onto the surviving factory.++ Zone code is TOLD to call ``build<Kept>(THREE, {variant: n})``, but a zone that+ imports the old name anyway must get the real prop, not the placeholder blockout+ box the skeleton left behind."""+ written: list[str] = []+ for dropped, kept in sorted(alias.items()):+ if kept not in available:+ continue+ rel = f"src/assets/{to_snake(dropped)}.js"+ path = ws.root / rel+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ f"// {dropped} is a variant of {kept} (assets were merged into one factory).\n"+ f"import {{ build{to_pascal(kept)} }} from './{to_snake(kept)}.js';\n\n"+ f"export function build{to_pascal(dropped)}(THREE, opts = {{}}) {{\n"+ f" return build{to_pascal(kept)}(THREE, {{ variant: {variant_index(alias, dropped)}, ...opts }});\n}}\n")+ written.append(rel)+ return writtendiff --git a/harness/codeverse/tracks/static_object.py b/harness/codeverse/tracks/static_object.pyindex beb86eaa..a9663e7f 100644--- a/harness/codeverse/tracks/static_object.py+++ b/harness/codeverse/tracks/static_object.py@@ -12,11 +12,26 @@ from collections.abc import Sequencefrom pathlib import Pathfrom typing import Any-from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet+from codeverse.contracts.artifacts import (+ BuildResult,+ GateFinding,+ GateReport,+ Measurement,+ RenderSet,+ RenderView,+ Severity,+)from codeverse.contracts.common import TRACK_INFO, Trackfrom codeverse.contracts.plan import Plan, StaticPlanfrom codeverse.contracts.run import RoundRecord-from codeverse.conventions import BBOX_TOLERANCE_M, OBJECT_VIEWS+from codeverse.conventions import (+ BBOX_TOLERANCE_M,+ LANGUAGE_FRAME,+ OBJECT_VIEWS,+ Frame,+ to_pascal,+ to_snake,+)from codeverse.orchestrator.rounds import DETAIL_KIND, RefineTask, TaskGroup, compact_instructionsfrom codeverse.prompts import renderfrom codeverse.tracks.common import RunContext@@ -26,7 +41,6 @@ from codeverse.tracks.depth import (scope_groups,scoped_generation_enabled,)-from codeverse.tracks.detailing import detail_instructions, drift_gatefrom codeverse.tracks.generation import GenerationTaskfrom codeverse.tracks.lifecycle import BaseTrackfrom codeverse.tracks.prompting import (@@ -44,7 +58,6 @@ from codeverse.tracks.prompting import (scope_context,skeleton_files,)-from codeverse.tracks.reference import reference_refine_tasks, silhouette_gatefrom codeverse.workspace import Workspacelog = logging.getLogger(__name__)@@ -452,3 +465,235 @@ class StaticObjectTrack(BaseTrack):f"compares every part's bounding box against the previous round and fails the round if one moved. "f"Everything you add lives inside or on an existing part's surface.")+++# ===================================================================== the DETAIL round+# (merged from codeverse/tracks/detailing.py, 2026-08-28 — this file was its only importer)+# --------------------------------------------------------------------------- detail-round drift gate+DRIFT_GATE = "detail_drift"+++def drift_findings(before: Any, after: Any, *, tol_m: float, language: str = "") -> list[Any]:+ """Did a detail round move anything? Findings for the ``detail_drift`` gate.++ The detail round's whole contract is "surface only": the silhouette, the part+ list and every part box stay put. This is the deterministic check of that+ promise — the judge is never asked whether the shape moved, code answers it.+ """+ from codeverse.contracts.artifacts import GateFinding, Severity++ out: list[Any] = []+ if before is None or after is None:+ return out+ for axis, a, b in zip(_axes(language), before.extents, after.extents, strict=True):+ d = float(b) - float(a)+ if abs(d) > tol_m:+ out.append(GateFinding(+ gate=DRIFT_GATE, severity=Severity.ERROR, target="overall",+ message=f"the detail round changed the overall {axis} extent by {d * 1000:+.1f} mm "+ f"({a:.3f} → {b:.3f} m); a detail round may not change the silhouette",+ fix_hint="revert whatever grew the object (a bevel that widened a part, a fastener sticking out) "+ "and keep the added geometry inside the existing surfaces",+ data={"kind": "detail_drift", "axis": axis, "delta_m": round(d, 5)}))+ was = {to_snake(str(p.name)): p for p in (before.parts or ())}+ now = {to_snake(str(p.name)): p for p in (after.parts or ())}+ for key in sorted(set(was) - set(now)):+ out.append(GateFinding(+ gate=DRIFT_GATE, severity=Severity.ERROR, target=to_pascal(key),+ message=f"part '{to_pascal(key)}' disappeared during the detail round",+ fix_hint=f"restore '{to_pascal(key)}' exactly as it was before this round",+ data={"kind": "detail_drift", "removed": key}))+ for key in sorted(set(now) - set(was)):+ out.append(GateFinding(+ gate=DRIFT_GATE, severity=Severity.WARN, target=to_pascal(key),+ message=f"the detail round introduced a new top-level part '{to_pascal(key)}'",+ fix_hint="detail belongs inside an existing part; merge it into the part it decorates "+ "(or accept it only if the plan names it)",+ data={"kind": "detail_drift", "added": key}))+ moved = 0+ for key in sorted(set(was) & set(now)):+ a, b = was[key], now[key]+ dc = max(abs((bl + bh) / 2 - (al + ah) / 2)+ for al, ah, bl, bh in zip(a.bbox_min, a.bbox_max, b.bbox_min, b.bbox_max, strict=True))+ de = max(abs((bh - bl) - (ah - al))+ for al, ah, bl, bh in zip(a.bbox_min, a.bbox_max, b.bbox_min, b.bbox_max, strict=True))+ if max(dc, de) <= tol_m:+ continue+ moved += 1+ if moved > 8:+ continue+ out.append(GateFinding(+ gate=DRIFT_GATE, severity=Severity.ERROR, target=to_pascal(key),+ message=f"part '{to_pascal(key)}' moved {dc * 1000:.1f} mm / resized {de * 1000:.1f} mm during the "+ f"detail round (tolerance {tol_m * 1000:.0f} mm)",+ fix_hint="put the part back on its previous centre and extents; add the detail inside that box",+ data={"kind": "detail_drift", "part": key, "centre_mm": round(dc * 1000, 2),+ "extent_mm": round(de * 1000, 2)}))+ if moved > 8:+ out.append(GateFinding(gate=DRIFT_GATE, severity=Severity.ERROR, target="overall",+ message=f"{moved} parts moved during the detail round ({moved - 8} more not listed)",+ fix_hint="revert the placement changes; this round may only add surface geometry",+ data={"kind": "detail_drift", "moved": moved}))+ if not out:+ d_tri = int(getattr(after, "tri_count", 0) or 0) - int(getattr(before, "tri_count", 0) or 0)+ out.append(GateFinding(gate=DRIFT_GATE, severity=Severity.INFO, target="overall",+ message=f"detail round held the contract: no part moved more than "+ f"{tol_m * 1000:.0f} mm; {d_tri:+,} triangles added",+ data={"kind": "detail_drift", "delta_tris": d_tri}))+ return out+++def _axes(language: str) -> tuple[str, str, str]:+ """Axis letters as the AUTHOR sees them. ``Measurement.extents`` is in the GLB frame+ (Y-up); a blender/cadquery/urdf author thinks Z-up, where glb (x, y, z) reads (x, z, y)+ — so naming the GLB axis in a fix hint would send them to the wrong dimension."""+ if LANGUAGE_FRAME.get(language) is Frame.Z_UP_NEG_Y_FRONT:+ return ("x", "z", "y")+ return ("x", "y", "z")+++def drift_gate(before: Any, after: Any, *, tol_m: float, language: str = "") -> Any:+ """``detail_drift`` GateReport (passing when nothing moved)."""+ from codeverse.contracts.artifacts import GateReport, Severity++ findings = drift_findings(before, after, tol_m=tol_m, language=language)+ return GateReport(gate=DRIFT_GATE, findings=findings,+ passed=not any(f.severity is Severity.ERROR for f in findings))+++# --------------------------------------------------------------------------- detail-round tasks+#: judge improvement-plan kinds a DETAIL round is allowed to act on. Assembly/placement+#: work is the repair loop's job and would break the no-drift contract.+DETAIL_KINDS = frozenset({"geometry", "detail", "material", "materials", "craftsmanship", "texture", "finish"})++#: what a detail round always does, whatever the judge said. Ordered by measured value per+#: triangle: edge treatment first (it changes how every surface reads under light), then the+#: features a viewer counts, then wear.+DEFAULT_DETAIL_LINES: tuple[str, ...] = (+ "Bevel or chamfer every hard edge that a real version of this object would have "+ "(2-6 mm on furniture and cast parts, 0.5-2 mm on sheet metal and small mechanisms).",+ "Add the panel lines, seams and shut-lines where the real object's shells meet "+ "(lids, drawers, housings, trays): 1-2 mm wide, ~1 mm deep insets.",+ "Add the fasteners the real object is held together with — bolt heads, rivets, screws, "+ "hinges — arrayed in a loop at the joints, sized 3-10 mm.",+ "Give each material family a distinct roughness/metalness and a slightly different value; "+ "no two different materials may share the same flat grey.",+)+++def detail_instructions(last: Any, plan: Any, *, max_lines: int = 8) -> list[str]:+ """Instruction lines for a detail round: the measured density gap first, then the+ judge's detail-shaped asks, then the standing detail vocabulary; deduped and capped."""+ lines: list[str] = []+ seen: set[str] = set()++ def _add(text: str) -> None:+ key = text.strip().lower()[:80]+ if key and key not in seen:+ seen.add(key)+ lines.append(text.strip())++ for g in getattr(last, "gates", None) or ():+ for f in getattr(g, "findings", None) or ():+ if (f.data or {}).get("kind") == "under_tri_budget":+ _add(f"{f.message}. {f.fix_hint}")+ j = getattr(last, "judgment", None)+ for item in sorted(getattr(j, "improvement_plan", None) or (),+ key=lambda i: (i.priority, -getattr(i, "expected_gain", 0.0))):+ if str(getattr(item, "kind", "")).lower() not in DETAIL_KINDS:+ continue+ target = getattr(item, "target", "") or "overall"+ _add(f"{target}: {item.instruction}")+ for issue in getattr(j, "issues", None) or ():+ if str(getattr(issue, "kind", "")).lower() in ("material", "materials", "detail"):+ _add(f"{issue.target or 'overall'}: {issue.detail}")+ for text in DEFAULT_DETAIL_LINES:+ _add(text)+ return lines[:max_lines]+++# ===================================================================== reference images+# (merged from codeverse/tracks/reference.py, 2026-08-28 — this file was its only importer,+# and nothing else, tests included, ever imported it)+SILHOUETTE_GATE = "reference_silhouette"+IOU_REFINE_THRESHOLD = 0.6+FRONT_VIEW_NAMES: tuple[str, ...] = ("front", "front_right_34", "front_left_34")+++def target_reference(ctx: RunContext) -> str | None:+ """Path of the reference image to match the silhouette against (role ``target`` first)."""+ refs = [r for r in ctx.spec.references if Path(r.path).is_file()]+ if not refs:+ return None+ return next((r.path for r in refs if r.role == "target"), refs[0].path)+++def front_view(renders: RenderSet) -> RenderView | None:+ for name in FRONT_VIEW_NAMES:+ for v in renders.views:+ if v.name == name:+ return v+ return renders.views[0] if renders.views else None+++def silhouette_gate(ctx: RunContext, renders: RenderSet) -> GateReport | None:+ """``None`` when the spec has no reference images or nothing could be compared."""+ ref = target_reference(ctx)+ view = front_view(renders)+ if ref is None or view is None:+ return None+ try:+ res = ctx.services.silhouette(view.path, ref)+ except Exception as e: # noqa: BLE001 — advisory measurement; never fails a round+ log.warning("compare_silhouette failed: %s", e)+ return GateReport(gate=SILHOUETTE_GATE, passed=True, findings=[GateFinding(+ gate=SILHOUETTE_GATE, severity=Severity.INFO, target="overall", message=f"silhouette comparison unavailable: {e}")])+ iou = float(res.get("iou", 0.0)) if isinstance(res, dict) else 0.0+ reliable = bool(res.get("reliable", True)) if isinstance(res, dict) else False+ data = {k: v for k, v in (res.items() if isinstance(res, dict) else []) if isinstance(v, (int, float, str, bool))}+ data["view"] = view.name+ data["reference"] = ref+ low = reliable and iou < IOU_REFINE_THRESHOLD+ msg = (f"front-view outline IoU vs reference = {iou:.3f}" + ("" if reliable else " (unreliable mask)")+ + (f" — below {IOU_REFINE_THRESHOLD:.1f}" if low else ""))+ finding = GateFinding(gate=SILHOUETTE_GATE, severity=Severity.WARN if low else Severity.INFO, target="overall",+ message=msg, data=data,+ fix_hint=("match the reference outline: compare proportions (aspect ratio), overall extents and the "+ "silhouette of each major part against the reference image" if low else ""))+ return GateReport(gate=SILHOUETTE_GATE, passed=True, findings=[finding])+++def silhouette_iou(rec: RoundRecord) -> tuple[float, dict] | None:+ """(iou, data) recorded by ``silhouette_gate`` in a round, if any."""+ for g in rec.gates:+ if g.gate != SILHOUETTE_GATE:+ continue+ for f in g.findings:+ if "iou" in f.data:+ try:+ return float(f.data["iou"]), dict(f.data)+ except (TypeError, ValueError):+ return None+ return None+++def reference_refine_tasks(ctx: RunContext, last: RoundRecord) -> list[RefineTask]:+ """A priority-1 refine task when the last round's silhouette IoU was below threshold."""+ if not ctx.spec.references:+ return []+ hit = silhouette_iou(last)+ if hit is None:+ return []+ iou, data = hit+ if iou >= IOU_REFINE_THRESHOLD or data.get("reliable") is False:+ return []+ bits = [f"Front-view silhouette IoU vs the reference image is {iou:.2f} (target ≥ {IOU_REFINE_THRESHOLD:.1f})."]+ aspect = data.get("aspect_ratio_err")+ if isinstance(aspect, (int, float)):+ ra, rr = data.get("ref_aspect"), data.get("render_aspect")+ if isinstance(ra, (int, float)) and isinstance(rr, (int, float)):+ bits.append(f"Aspect (w/h): reference {ra:.2f} vs model {rr:.2f} — " ++ ("make the object wider relative to its height" if rr < ra else "make the object taller relative to its width") + ".")+ bits.append("Re-read the reference: match the outline of every major part (overall proportions first, then part shapes), "+ "keeping names and the plan's dimensions unless the reference clearly disagrees.")+ return [RefineTask(target="overall", kind="reference", instruction=" ".join(bits), priority=1, source="gate")]diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex e2f0a101..b829cb74 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -93,18 +93,18 @@ codeverse/lines so it stays a leaffanout.py bounded parallel fan-out (fan_out, split_results, FanOutReport) — shared bytracks/judges/texturing/bench- models/ ChatModel; gemini_convert.py anthropic_convert.py openai_convert.py+ models/ ChatModel (base.py); gemini_convert.py anthropic_convert.py openai_convert.py(request/response shapes per provider), parts.py; gemini.py (dead-key + free 429 rotation), gemini_image.py (ImageModel),anthropic.py openai.py, keypool.py ('dead' outcome + TPM reservation/reconcile),tokens.py (prompt-token estimate for the TPM bucket), pricing.py (version-suffix-onlyfallback), retry.py (MAX_WAIT_S: no single wait > 3 s), storm.py (shared 503 gate —measured, ships OFF, see docs/COST.md §21), health.py (preflight probe: is the modelserving? no retries, no backoff), schema_utils.py (strict schema), registry.py- agents/ CodingAgent; gemini_cli.py claude_code.py codex.py antigravity.py+ agents/ CodingAgent (base.py); gemini_cli.py claude_code.py codex.py antigravity.py(api_agent.py + api_tools.py + api_skills.py deleted 2026-08-28 —the vendors already ship the loop), materialize.py, cli_common.py (sessions, retrytrajectory naming, files_changed attribution), watchdog.py, transcript.py, registry.py- languages/ LanguageRuntime; blender/ (multi-file: layout.py, model.py + parts/*.py) cadquery/+ languages/ LanguageRuntime (base.py); blender/ (multi-file: layout.py, model.py + parts/*.py) cadquery/threejs/ (+ templates.py) urdf/ scene_threejs/ glsl_shader/ (wrap.py header+line-map)opengl_python/ (wrappers/run_gl.py) — each runtime.py, lint.py, skeleton.py, wrappers/;file_lint.py (one just-written file → syntax/lint verdict for write_file, COST.md §29)@@ -141,7 +141,7 @@ codeverse/billing.py (SUBSCRIPTION_BACKENDS/bills_usd — which backends take real dollars,so max_usd guards money and not list price; docs/COST.md §25)guard.py routing.py reconstruct.py (old runs) audit.py report.py- judges/ rubrics.py + rubrics/*.yaml (defect checklists), vlm_judge.py, montage.py,+ judges/ base.py (Judge protocol), rubrics.py + rubrics/*.yaml (defect checklists), vlm_judge.py, montage.py,prompt_builder.py, output_schema.py, scoring.py, caps.py, images.py, pairwise.py(compare_many), reference.py, calibration.py, metrics.py, replay_input.py(plan_digest / resolve_paths / judged_subset — the pure round-replay pieces@@ -156,12 +156,15 @@ codeverse/unwrap), apply.py, gate.py (seam + before/after judge), scene_pack.py, run.py (texture_pass),maps.py (PBR map set), materials.py (named material library), normalise.pyorchestrator/ runner.py, state.py, rounds.py (RoundPolicy, StopPolicy, BestSelector), refine_tasks.py- (RefineTask compilation + file-ownership grouping + compaction), candidates.py (best-of-N- + pairwise decisions), budget.py- tracks/ base.py (get_track(track, **options)), lifecycle.py, steps.py, candidates.py,- generation.py, repair.py, planner.py, prompting.py (prompt helpers, split from common),- common.py (RunContext, Services), motion.py, reference.py, static_object.py,- articulated_object.py, scene.py, scene_assets.py, graphics.py + graphics_steps.py,+ (RefineTask compilation + file-ownership grouping + compaction), budget.py+ tracks/ __init__.py (get_track(track, **options) + the TrackPipeline protocol),+ lifecycle.py, steps.py, candidates.py (best-of-N + the pure candidate/pairwise+ decision logic), generation.py (agent + single-shot strategies + the file+ envelope), repair.py, planner.py, prompting.py (prompt helpers, split from common),+ common.py (RunContext, Services), static_object.py (+ the detail round and the+ reference-image gates), articulated_object.py (+ the planned-motion gate),+ scene.py, scene_assets.py (+ cheap single-shot asset generation),+ graphics.py + graphics_steps.py,graphics_recipes.py (the brief's verified cookbook recipes + their helpers written intothe harness-owned, read-only src/recipes.glsl before the session — measured: flash callsa recipe on disk, not one it is shown, and overwrites one seeded into its own common.glsl;@@ -172,8 +175,7 @@ codeverse/plan_features.py (CV3D_PLAN_FEATURES: one switch per plan-loop change, so eachcan be A/B'd alone, + pin_plan_blockers() deciding when two arms may shareone plan — docs/PLAN_LOOP.md, docs/EVAL.md §8.1),- plan_examples.py (worked plans shown to the planner), depth.py + detailing.py- (per-part detail pass), envelope.py (bbox envelope), scene_asset_gen.py,+ plan_examples.py (worked plans shown to the planner), depth.py,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/INTERFACES.md b/harness/docs/INTERFACES.mdindex 55f4f0a8..0db3a26b 100644--- a/harness/docs/INTERFACES.md+++ b/harness/docs/INTERFACES.md@@ -2,7 +2,7 @@This file lists the signatures other packages may rely on. Types live in`codeverse/contracts/`; protocols in `models/base.py`, `agents/base.py`,-`languages/base.py`, `spatial/registry.py`, `judges/base.py`, `tracks/base.py`.+`languages/base.py`, `spatial/registry.py`, `judges/base.py`, `tracks/__init__.py`.Where the build deviated from the original plan the deviation is called out as**Δ** — see `docs/DECISIONS.md` for the why. When in doubt the code wins; thisfile was reconciled against it on 2026-08-23 (waves 2–3 + fix batch 1).@@ -336,12 +336,12 @@ BudgetGuard(budget, *, soft_fraction=1.0, run="", ledger=None)# (skipped when cost.instrument.per_call_metering() already writes them) → enforce the ceilings.# charge(...) = spend(enforce=True); add(...) = spend(enforce=False) — "not enforced" never means "not seen"..by_stage / .by_round / .round_costs(i) / .stage_summary() / .mark() # what a round burned, live-from codeverse.orchestrator.candidates import CandidateRecord, rank_candidates, decide_best # pure decision logic+from codeverse.tracks.candidates import CandidateRecord, rank_candidates, decide_best # pure decision logicfrom codeverse.tracks.candidates import run_best_of_n, choose_best_round # N parallel baselines in <ws>/_cand/c<k># (quick 4-view judge, crashed candidate retried once; selection by build_ok → quick score → fewer gate errors, pairwise# within margin); winner copied back, normal r00 pipeline follows; rounds/candidates.json + record.extra["candidates"]-from codeverse.tracks.motion import default_motion_checks, expected_direction # gate "motion_direction" (articulated)-from codeverse.tracks.reference import silhouette_gate, reference_refine_tasks # gate "reference_silhouette" (IoU<0.6 → WARN + refine task)+from codeverse.tracks.articulated_object import default_motion_checks, expected_direction # gate "motion_direction"+from codeverse.tracks.static_object import silhouette_gate, reference_refine_tasks # gate "reference_silhouette" (IoU<0.6 → WARN + refine task)from codeverse.tracks.depth import depth_budget, DepthBudget, scope_groups, PartScope, interfaces_text, \scoped_generation_enabled # complexity-aware budgets + per-part scoped generationdepth_budget(plan, *, build_timeout_s=300) -> DepthBudget # min/target/max triangles + max_build_s sized from@@ -351,7 +351,7 @@ scope_groups(plan, *, files_for, max_groups=6, parts_per_scope=3, min_parts=8) -# [] = one session owns the object (small plan, no per-part file ownership, or $CV3D_SCOPED_PARTS=off);# otherwise attachment-subtree groups whose files are disjoint, so the sessions run in parallelinterfaces_text(plan, scope) -> str # the planned boxes of the neighbours this scope must weld to-from codeverse.tracks.detailing import drift_gate, detail_instructions, DRIFT_GATE # gate "detail_drift":+from codeverse.tracks.static_object import drift_gate, detail_instructions, DRIFT_GATE # gate "detail_drift":# ERROR when a detail round moved/resized/removed a part or changed the overall extents (tol from policy)from codeverse.tracks.prompting import base_prompt_context, reference_images, file_for_target_factory, \scope_context, budget_for, detail_budget_text # Δ split out ofdiff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.mdindex 0c45b9cd..97a2d86e 100644--- a/harness/docs/RUNBOOK.md+++ b/harness/docs/RUNBOOK.md@@ -260,7 +260,7 @@ model, produced the zero — check `cell.json`'s `error`).CodingAgent → `agents/<kind>.py` using `cli_common` + registry + `materialize.py`.* **New track**: subclass `tracks/lifecycle.py::BaseTrack` (hooks: `make_pipeline`,`prepare`, `baseline_tasks`, `refine_tasks`, `round_files_hint`), a `RoundPipeline`,- plan model in `contracts/plan.py`, `.j2` prompts, branch in `tracks/base.py`+ plan model in `contracts/plan.py`, `.j2` prompts, branch in `tracks/__init__.py`(`get_track` forwards `**options` to constructors). `tracks/graphics.py` is thetemplate for a track with its own planner and no GLB.* **New bench battery**: `bench/prompts/<name>.yaml` with `name, track, language,diff --git a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.pyindex feb3da23..76b3c634 100644--- a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py+++ b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py@@ -12,7 +12,6 @@ from codeverse.contracts.plan import ArticulatedPlanfrom codeverse.contracts.run import RunStatusfrom codeverse.contracts.spec import ReferenceImagefrom codeverse.events import EventLog-from codeverse.orchestrator.candidates import CandidateRecord, decide_best, rank_candidatesfrom codeverse.orchestrator.rounds import (RefineTask,RoundPolicy,@@ -20,8 +19,8 @@ from codeverse.orchestrator.rounds import (compact_instructions,)from codeverse.tracks import get_track-from codeverse.tracks.articulated_object import ArticulatedObjectTrack-from codeverse.tracks.motion import expected_direction+from codeverse.tracks.articulated_object import ArticulatedObjectTrack, expected_direction+from codeverse.tracks.candidates import CandidateRecord, decide_best, rank_candidatesfrom codeverse.tracks.planner import plan_examplefrom codeverse.tracks.static_object import StaticObjectTrackfrom codeverse.workspace import Workspace@@ -346,7 +345,7 @@ def test_default_motion_checks_on_real_urdf(tmp_path):import trimeshfrom codeverse.contracts.plan import BBox, JointPlan, PartPlan- from codeverse.tracks.motion import default_motion_checks+ from codeverse.tracks.articulated_object import default_motion_checksdef robot(root, axis_z):ws = Workspace(root).create()diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.pyindex dadda70f..a2003893 100644--- a/harness/tests/orchestrator_tracks/test_cost_latency.py+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py@@ -20,15 +20,16 @@ from codeverse.orchestrator.state import RunStatefrom codeverse.tracks.common import RunContextfrom codeverse.tracks.planner import plan_examplefrom codeverse.tracks.scene import SceneTrack, plan_zone_batches, zone_file-from codeverse.tracks.scene_asset_gen import (+from codeverse.tracks.scene_assets import (+ asset_api_summary,check_threejs_asset,dedupe_assets,+ run_asset_stage,select_assets,single_shot_agent_id,single_shot_ctx,variant_index,)-from codeverse.tracks.scene_assets import asset_api_summary, run_asset_stagefrom codeverse.workspace import Workspacefrom tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import (diff --git a/harness/tests/orchestrator_tracks/test_generation_depth.py b/harness/tests/orchestrator_tracks/test_generation_depth.pyindex a06254fa..abb07f54 100644--- a/harness/tests/orchestrator_tracks/test_generation_depth.py+++ b/harness/tests/orchestrator_tracks/test_generation_depth.py@@ -39,7 +39,7 @@ from codeverse.tracks.depth import (scope_groups,scoped_generation_enabled,)-from codeverse.tracks.detailing import DRIFT_GATE, detail_instructions, drift_gate+from codeverse.tracks.static_object import DRIFT_GATE, detail_instructions, drift_gatefrom .conftest import make_specfrom .fakes import FakeAgent, FakeRuntime, FakeServices@@ -351,7 +351,7 @@ def test_a_full_run_spends_exactly_one_detail_round_after_the_plateau(tmp_path,"""End to end on fakes: flat scores → plateau → ONE round of kind 'detail', gated bydetail_drift, and never a second one."""from codeverse.contracts.run import RunStatus- from codeverse.tracks.detailing import DRIFT_GATE as _DRIFT+ from codeverse.tracks.static_object import DRIFT_GATE as _DRIFTfrom codeverse.tracks.static_object import StaticObjectTrackfrom codeverse.workspace import Workspacediff --git a/harness/tests/orchestrator_tracks/test_scene_asset_checker_race.py b/harness/tests/orchestrator_tracks/test_scene_asset_checker_race.pyindex 6e4196ee..95394684 100644--- a/harness/tests/orchestrator_tracks/test_scene_asset_checker_race.py+++ b/harness/tests/orchestrator_tracks/test_scene_asset_checker_race.py@@ -15,7 +15,7 @@ from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom types import SimpleNamespace-from codeverse.tracks.scene_asset_gen import _CHECK_JS, _checker_path+from codeverse.tracks.scene_assets import _CHECK_JS, _checker_pathdef _ctx(cache: Path) -> SimpleNamespace:diff --git a/harness/tests/orchestrator_tracks/test_write_scope.py b/harness/tests/orchestrator_tracks/test_write_scope.pyindex 8e629de4..d8ae5986 100644--- a/harness/tests/orchestrator_tracks/test_write_scope.py+++ b/harness/tests/orchestrator_tracks/test_write_scope.py@@ -19,13 +19,13 @@ from codeverse.contracts.run import RoundRecordfrom codeverse.events import EventLogfrom codeverse.orchestrator.rounds import RefineTask, TaskGroupfrom codeverse.orchestrator.state import RunState-from codeverse.tracks.envelope import write_filesfrom codeverse.tracks.generation import (GenerationResult,GenerationTask,_always_writable,generate_files,run_agent_task,+ write_files,)from codeverse.tracks.planner import plan_examplefrom codeverse.tracks.scene import SceneTrack, zone_file