Official Codebase of 3DCodeVerse
Python
judge/texture/zone fixes from the PR #3 review sweep — every finding reproduced or refuted first
gaoypeng83408ba54b9d
diff --git a/harness/codeverse/judges/prompt_builder.py b/harness/codeverse/judges/prompt_builder.pyindex d89cc8ca..3450e3ba 100644--- a/harness/codeverse/judges/prompt_builder.py+++ b/harness/codeverse/judges/prompt_builder.py@@ -145,9 +145,13 @@ GEOMETRY_MODES = tuple(m for m in RENDER_MODES if m != "shaded")#: montage 1 = {front_right_high, back_left_high, top, bottom}, so a montage-cap#: truncation still sees the underside; then the eye ring, then the remaining rings.OBJECT_RANK = (- "front_right_high", "back_left_high", "top", "bottom",+ # legacy pre-D47 names ride beside their D47 twins so a STORED 8-view run+ # re-judges with the same montage shape the in-run judge saw (3/4 heroes first)+ # — DIFF_VIEW_NAMES / CANDIDATE_VIEWS / FRONT_VIEW_NAMES / HERO_PREFERENCE all+ # kept them; this one had forgotten (review of PR #3)+ "front_right_high", "front_right_34", "back_left_high", "back_left_34", "top", "bottom","front", "right", "back", "left",- "front_right_low", "back_left_low", "front_left_high", "back_right_high",+ "front_right_low", "low_front_left", "back_left_low", "front_left_high", "back_right_high","front_left_low", "back_right_low",)#: scene rig: authored cameras first (graded for composition), then the overview rig.diff --git a/harness/codeverse/judges/vlm_judge.py b/harness/codeverse/judges/vlm_judge.pyindex d17d69f4..efb14d35 100644--- a/harness/codeverse/judges/vlm_judge.py+++ b/harness/codeverse/judges/vlm_judge.py@@ -128,12 +128,22 @@ class VlmJudge:# payload size: the profile's dial (Settings.judge) unless the caller states onejd = get_settings().judgeself.max_montages = max(1, int(jd.montages if max_montages is None else max_montages))+ self._montages_explicit = max_montages is not Noneself.detail_crops = max(0, int(jd.detail_crops if detail_crops is None else detail_crops))self.max_px = int(jd.max_px if max_px is None else max_px)self._model = chat_modelself.cache_dir = cache_dirself.label = label+ def _montages_for(self, inp: JudgeInput) -> int:+ """Per-track montage cap: the 3→5 default was measured ONLY on the D47 object+ rig (docs/DECISIONS.md D47); scene and graphics keep the pre-D47 ceiling of 3+ until a battery measures them at 5 (review of PR #3). An explicit+ ``max_montages`` from the caller always wins."""+ if self._montages_explicit or inp.spec.track.value in SLICE_TRACKS:+ return self.max_montages+ return min(self.max_montages, 3)+# ------------------------------------------------------------------ provenance@propertydef prompt_hash(self) -> str:@@ -167,7 +177,7 @@ class VlmJudge:seed = None if (self.fixed_order or (self.n_samples == 1 and k == 0)) else (inp.round_index * 1000 + k)# a missing render is a pipeline bug, not a judge glitch → JudgeImageError propagatessystem, messages = build_judge_messages(- inp, self.rubric, shuffle_seed=seed, geometry_views=geometry_views, max_montages=self.max_montages,+ inp, self.rubric, shuffle_seed=seed, geometry_views=geometry_views, max_montages=self._montages_for(inp),detail_crops=self.detail_crops, max_px=self.max_px, cache_dir=self.cache_dir,extra_images=extra_images, extra_text=extra_text,slice_images=slice_images, provenance_elicitation=elicit,diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.pyindex 93328c47..86089f39 100644--- a/harness/codeverse/spatial/tools.py+++ b/harness/codeverse/spatial/tools.py@@ -698,8 +698,12 @@ def texture_pass_tool(ctx: ToolContext, args: TexturePassArgs) -> Observation:"3dcv make ... --texture # or `3dcv texture pass <slug>` after the run")texture_pass = lazy("codeverse.texturing.run", "texture_pass")services = ctx.extra.get("texture_services") # the ONE injection point (TextureServices)+ # update_record=False: during an agent session the control files have ONE owner+ # (finalise); a mid-session record.json write is reverted by the tamper enforcement+ # and fails the paid session — finalise collects the report into the record insteadrep = texture_pass(ctx.workspace, spec, plan, model_id=args.model or spec.backends.planner,- judge=args.judge, glb_in=glb, size=args.size, services=services)+ judge=args.judge, glb_in=glb, size=args.size, services=services,+ update_record=False)s = rep.summary()root = ctx.workspace.rootlines = [diff --git a/harness/codeverse/texturing/generate.py b/harness/codeverse/texturing/generate.pyindex 7c35c8e8..31fcb077 100644--- a/harness/codeverse/texturing/generate.py+++ b/harness/codeverse/texturing/generate.py@@ -13,7 +13,6 @@ from __future__ import annotationsimport hashlibimport logging-import osimport shutilimport timefrom collections.abc import Callable, Sequence@@ -32,7 +31,7 @@ from codeverse.contracts.spec import Specfrom codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPresetfrom codeverse.judges.base import JudgeInput, plan_digestfrom codeverse.judges.rubrics import is_degraded-from codeverse.proc import fan_out+from codeverse.proc import fan_out, unique_tmp#: seam score above which a texture is considered NOT tileable (after make_tileable)SEAM_MAX = 0.08@@ -186,9 +185,15 @@ def generate_one(raw = images[0].convert("RGB")asset.usage = usageif use_cache:- tmp = raw_path.with_suffix(f".{os.getpid()}.tmp.png") # per-writer: a cross-process collision poisoned the shared cache- raw.save(tmp, "PNG")- tmp.replace(raw_path)+ # per-writer tmp (pid AND thread — candidates fan out over threads in ONE+ # process, so a pid-only name is still a race: review of PR #3); tolerant+ # replace like every other cache publish+ tmp = unique_tmp(raw_path)+ try:+ raw.save(tmp, "PNG")+ tmp.replace(raw_path)+ finally:+ tmp.unlink(missing_ok=True)asset.seam_score_raw = seam_score(raw)img = fit_size(raw, size)if tileable:diff --git a/harness/codeverse/texturing/plan.py b/harness/codeverse/texturing/plan.pyindex 1516a0cf..5a0eb6e8 100644--- a/harness/codeverse/texturing/plan.py+++ b/harness/codeverse/texturing/plan.py@@ -11,7 +11,6 @@ from __future__ import annotationsimport hashlibimport jsonimport logging-import osfrom collections.abc import Sequencefrom pathlib import Pathfrom typing import Any, Literal@@ -26,6 +25,7 @@ from codeverse.contracts.plan import PartPlan, ScenePlan, StaticPlanfrom codeverse.contracts.spec import Specfrom codeverse.conventions import to_snakefrom codeverse.models.schema_utils import ask_structured+from codeverse.proc import write_text_atomicfrom codeverse.prompts import load_text, prompt_hash, renderfrom codeverse.texturing.generate import TextureSet, generate_textures@@ -325,10 +325,9 @@ def material_plan(raise ValueError(f"texture planner: {err}")tp = finalize_plan(out, plan, model_id=model_id, usage=usage, source="vlm")if use_cache:- cache_root.mkdir(parents=True, exist_ok=True)- tmp = cached.with_suffix(f".{os.getpid()}.tmp") # atomic: a torn sidecar re-bought the VLM call- tmp.write_text(tp.model_dump_json(indent=2))- tmp.replace(cached)+ # pid+thread tmp + rename (a torn sidecar re-bought the VLM call; a pid-only+ # name raced between threads of one process — review of PR #3)+ write_text_atomic(cached, tp.model_dump_json(indent=2))return tpdiff --git a/harness/codeverse/texturing/run.py b/harness/codeverse/texturing/run.pyindex c1733806..4d7aaf31 100644--- a/harness/codeverse/texturing/run.py+++ b/harness/codeverse/texturing/run.py@@ -309,6 +309,11 @@ def _finish(ws: Workspace, report: TextureReport, t0: float, events: EventLog, ureturn report+def report_path(ws: Workspace) -> Path:+ """THE location of the texture report — the finalise double-buy guard reads it too."""+ return ws.artifacts / TEXTURES_DIR / REPORT_NAME++def record_texturing(ws: Workspace, report: TextureReport) -> bool:"""``record.json`` extra["texturing"] = summary (+ asset paths) when a record exists."""if not ws.record_path.is_file():@@ -318,19 +323,25 @@ def record_texturing(ws: Workspace, report: TextureReport) -> bool:except json.JSONDecodeError:return Falseextra = data.setdefault("extra", {})- extra["texturing"] = {+ extra["texturing"] = texturing_extra(ws, report)+ ws.write_json(ws.record_path, data)+ return True+++def texturing_extra(ws: Workspace, report: TextureReport) -> dict[str, Any]:+ """The ``extra["texturing"]`` payload — ONE builder for the record write here and the+ finalise-side collect (a tool-textured session no longer writes record.json itself)."""+ return {**report.summary(),"glb_textured": str(Path(report.glb_out).relative_to(ws.root)) if report.glb_out else "","textures_dir": f"artifacts/{TEXTURES_DIR}","textures": {tid: Path(a.path).name for tid, a in report.textures.textures.items() if a.ok},"texture_plan": {p.part: p.texture_id for p in report.plan.textured()},}- ws.write_json(ws.record_path, data)- return Truedef load_report(ws: Workspace) -> TextureReport:- p = ws.artifacts / TEXTURES_DIR / REPORT_NAME+ p = report_path(ws)if not p.is_file():raise FileNotFoundError(f"no texturing report at {p}")return TextureReport.model_validate_json(p.read_text())diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.pyindex 9460d6a9..97bea528 100644--- a/harness/codeverse/tracks/lifecycle.py+++ b/harness/codeverse/tracks/lifecycle.py@@ -820,8 +820,16 @@ class BaseTrack:if self._already_textured(ctx):# An agent can call the `texture_pass` spatial tool during a round; the# finalise hook must not buy the same pack a second time (a texture pass- # is $0.10-0.30 and the input GLB is unchanged).+ # is $0.10-0.30 and the input GLB is unchanged). The tool no longer writes+ # record.json mid-session (control files have one owner), so the report is+ # collected into the record here.ctx.events.emit("texture.skipped", reason="already_textured_this_artifact")+ try: # a malformed report must not block finalise+ from codeverse.texturing.run import load_report, texturing_extra++ ctx.extra["texturing"] = texturing_extra(ctx.ws, load_report(ctx.ws))+ except Exception: # noqa: BLE001+ log.warning("tool-textured report could not be collected into the record")returntry:from codeverse.texturing.run import texture_pass@@ -847,13 +855,17 @@ class BaseTrack:def _already_textured(ctx: RunContext) -> bool:"""True when a texture pass already ran against the current ``object.glb``.- The report (``artifacts/texturing.json``) records the GLB it consumed; the+ The report (``artifacts/textures/texturing.json``) records the GLB it consumed+ — reading it at ``artifacts/texturing.json`` made this guard dead code and the+ finalise pass double-bought every tool-textured pack (review of PR #3); thehook compares content hashes so a texture pass from an EARLIER round (whoseGLB has since been rebuilt) does not suppress the final one."""import hashlibimport json as _json- report = ctx.ws.artifacts / "texturing.json"+ from codeverse.texturing.run import report_path++ report = report_path(ctx.ws)glb = ctx.ws.artifacts / "object.glb"if not report.is_file() or not glb.is_file():return Falsediff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.pyindex 57b7bbf4..7c94abad 100644--- a/harness/codeverse/tracks/planner.py+++ b/harness/codeverse/tracks/planner.py@@ -575,7 +575,9 @@ PLAN_GEOMETRY_ENV = "CV3D_PLAN_GEOMETRY"def geometry_check_enabled() -> bool:- return os.environ.get(PLAN_GEOMETRY_ENV, "0").strip().lower() in ("1", "true", "on", "yes")+ from codeverse.config import env_flag # ONE flag vocabulary (review-3 S4)++ return env_flag(PLAN_GEOMETRY_ENV, False)#: Output room for the plan call, sized from the plan budget. A deep plan is much longer#: JSON than a flat one AND Gemini 3.x bills its thinking against the same ceiling, so the#: flat 24 000 that served 8 box-parts truncates a 12-part plan with sub-parts —diff --git a/harness/runtime_js/lib/host_metrics.mjs b/harness/runtime_js/lib/host_metrics.mjsindex 7d23e882..8b04c365 100644--- a/harness/runtime_js/lib/host_metrics.mjs+++ b/harness/runtime_js/lib/host_metrics.mjs@@ -103,8 +103,9 @@ export function nearGeometry(scene, camera, THREE, limitM = 0.3) {}/**- * Deterministic camera repair, added 2026-08-30 and OFF by default- * (drivers pass --camera-repair; python gates it behind CV3D_CAMERA_REPAIR=1).+ * Deterministic camera repair, added 2026-08-30; ON by default since 3f463ce+ * (drivers pass --camera-repair; python's probe_env_args() disables it only when+ * CV3D_CAMERA_REPAIR says false/off/no/0).** Why: cameras belong to the PLAN — no refine agent owns a file that could fix* one, so camera_in_geometry stood in final rounds across whole batteriesdiff --git a/harness/tests/judges/test_montage.py b/harness/tests/judges/test_montage.pyindex f9c2cd5c..a52d2e34 100644--- a/harness/tests/judges/test_montage.py+++ b/harness/tests/judges/test_montage.py@@ -141,3 +141,15 @@ def test_sheet_helpers(tmp_path):assert im.size == (600, 600)with pytest.raises(ValueError):crop_region(src, tmp_path / "c2.png", (0.5, 0.5, 0.5, 0.9))+++def test_a_stored_pre_d47_render_set_still_leads_with_its_hero_views():+ """PR #3 review: OBJECT_RANK forgot the legacy names, so a re-judged stored 8-view+ run put {top, front, right, back} in montage 1 and anchored the centre crop on+ 'top' — its four sibling constants all kept the legacy names for stored runs."""+ from codeverse.contracts.artifacts import RenderView+ from codeverse.judges.prompt_builder import rank_views++ legacy = ["front_right_34", "back_left_34", "front", "right", "back", "left", "top", "low_front_left"]+ ranked = [v.name for v in rank_views([RenderView(name=n, path=f"/x/{n}.png") for n in legacy], scene=False)]+ assert ranked[:2] == ["front_right_34", "back_left_34"], rankeddiff --git a/harness/tests/judges/test_vlm_judge.py b/harness/tests/judges/test_vlm_judge.pyindex eab634e8..569d279a 100644--- a/harness/tests/judges/test_vlm_judge.py+++ b/harness/tests/judges/test_vlm_judge.py@@ -304,3 +304,25 @@ def test_the_last_attempt_still_gets_a_real_try(judge_input, cache_dir, monkeypamodel = FakeChatModel([nearly_spent, good_reply(R, IDS, 0.8)])j = _judge(model, cache_dir=cache_dir).judge(judge_input)assert j.passed and [r.max_wait_s for r in model.requests] == [SAMPLE_BUDGET_S, SAMPLE_MIN_WAIT_S]+++def test_scene_and_graphics_keep_the_pre_d47_montage_ceiling():+ """PR #3 review: montages 3→5 was measured only on the D47 object rig; the other+ tracks keep 3 until someone measures them, and an explicit caller value wins."""+ from codeverse.contracts.artifacts import RenderSet+ from codeverse.contracts.common import Language, Track+ from codeverse.contracts.spec import Spec+ from codeverse.judges.base import JudgeInput+ from codeverse.judges.vlm_judge import VlmJudge++ def inp(track, language):+ spec = Spec(id="t", track=track, language=language, prompt="p")+ return JudgeInput(spec=spec, renders=RenderSet(), gates=[], acceptance=[])++ j = VlmJudge("scene_v1", model_id="fake:fake-1")+ assert j._montages_for(inp(Track.SCENE, Language.SCENE_THREEJS)) == 3+ assert j._montages_for(inp(Track.GRAPHICS, Language.GLSL_SHADER)) == 3+ jo = VlmJudge("static_object_v1", model_id="fake:fake-1")+ assert jo._montages_for(inp(Track.STATIC_OBJECT, Language.BLENDER)) == 5+ explicit = VlmJudge("scene_v1", model_id="fake:fake-1", max_montages=5)+ assert explicit._montages_for(inp(Track.SCENE, Language.SCENE_THREEJS)) == 5diff --git a/harness/tests/orchestrator_tracks/test_integrations2.py b/harness/tests/orchestrator_tracks/test_integrations2.pyindex 805e6455..e57fb981 100644--- a/harness/tests/orchestrator_tracks/test_integrations2.py+++ b/harness/tests/orchestrator_tracks/test_integrations2.py@@ -178,3 +178,36 @@ def test_get_track_graphics_accepts_options(settings):t = get_track("graphics", settings=settings, n_candidates=2)assert isinstance(t, GraphicsTrack) and t._n_candidates == 2assert isinstance(get_track(Track.GRAPHICS), GraphicsTrack)+++def test_a_tool_textured_run_is_not_double_bought_and_still_records(tmp_path, chair_plan, settings, monkeypatch):+ """PR #3 review: the double-buy guard read ``artifacts/texturing.json`` while the+ report is written to ``artifacts/textures/texturing.json`` — dead code, so every+ re-finalise re-bought the pack; and the mid-session ``record.json`` write the tool+ used to make is now forbidden (control files have ONE owner during a session), so+ finalise must collect the report into ``extra['texturing']`` itself."""+ import codeverse.texturing.run as trun++ calls = []++ def fake_texture_pass(ws, spec, plan, **kw):+ calls.append(1)+ report = trun.TextureReport(+ plan=trun.TexturePlan(), textures=trun.TextureSet(), seam=trun.SeamGateResult(),+ glb_in=str(ws.artifacts / "object.glb"), shipped=True)+ ws.write_json(trun.report_path(ws), report.model_dump(mode="json"))+ return SimpleNamespace(usage=Usage(backend="fake", cost_usd=0.02),+ summary=lambda: {"shipped": True, "n_textures": 1})++ monkeypatch.setattr(trun, "texture_pass", fake_texture_pass)+ rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings, tags=["texture"])+ assert calls == [1] and rec.extra["texturing"]["shipped"] is True++ # a resume re-finalises: the guard must SKIP the pass (report's glb matches) and+ # still carry extra['texturing'] built from the report on disk+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(_agent_writer),+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,+ runtime=FakeRuntime(Language.THREEJS))+ rec2 = track.run(make_spec(max_rounds=0, tags=["texture"]), ws, resume=True)+ assert calls == [1], "the pack must not be bought a second time"+ assert rec2.extra["texturing"]["shipped"] is True, "the report is collected into the record at finalise"diff --git a/harness/tests/orchestrator_tracks/test_prompts_assets.py b/harness/tests/orchestrator_tracks/test_prompts_assets.pyindex ef8909ec..62d13b12 100644--- a/harness/tests/orchestrator_tracks/test_prompts_assets.py+++ b/harness/tests/orchestrator_tracks/test_prompts_assets.py@@ -85,6 +85,7 @@ def test_all_track_templates_exist_and_render(tmp_ws, settings, chair_plan):@pytest.mark.blender[email protected] # its threejs sibling asset runs the node import checkdef test_scene_templates_render_and_asset_stage_with_blender(tmp_ws, settings):plan = ScenePlan.model_validate(plan_example(Track.SCENE))spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)