Official Codebase of 3DCodeVerse
Python
bench: harness-vs-one-shot for the scene and graphics tracks
gaoypengeea3893eb739
diff --git a/harness/bench/_fixed_eval.py b/harness/bench/_fixed_eval.pyindex bca04a91..2773a419 100644--- a/harness/bench/_fixed_eval.py+++ b/harness/bench/_fixed_eval.py@@ -2,7 +2,8 @@``FixedEvaluator.evaluate(ws, spec)``: the cell's runtime lint + build → ``measure_glb``→ connectivity gate → 14-view ``render_glb`` (articulated: + joint sweep + pose sheet;-graphics: the frame sheet) → ``judge_for(spec)`` — a ``VlmJudge`` (or ``LikenessJudge``+graphics: the frame sheet; scene: authored cameras + orbit rig at two times + the+scene_frames gate) → ``judge_for(spec)`` — a ``VlmJudge`` (or ``LikenessJudge``for graphics with reference photos) on ``rubric_for(spec)``, the track's ``TRACK_INFO``rubric, the ONE track→rubric mapping of the compare bench. The judge's acceptance checklist is the brief's``must_have`` list (``acceptance_from_spec``) so harness and one-shot arms are@@ -143,6 +144,8 @@ class FixedEvaluator:out = EvalOutcome(build=build, lint=lint, gates=[lint])if build.ok and spec.track is Track.GRAPHICS:return self._evaluate_frames(ws, spec, out)+ if build.ok and spec.track is Track.SCENE:+ return self._evaluate_scene(ws, spec, out)if not build.ok or not build.glb_path:return outtry:@@ -169,6 +172,23 @@ class FixedEvaluator:return out+ def _evaluate_scene(self, ws: Workspace, spec: Spec, out: EvalOutcome) -> EvalOutcome:+ """Scene: the authored cameras plus the orbit rig at t = 0 and 1.5 s, the scene_frames gate,+ the scene rubric — the pictures the loop's judge sees, minus the loop's plan (2026-09-07:+ the compare bench had no scene branch, so a scene cell built, then returned unjudged)."""+ from codeverse.judges.base import JudgeInput+ from codeverse.spatial.frame_metrics import frame_gate_from_renders+ from codeverse.spatial.render_scene import render_scene+ try:+ out.renders = render_scene(ws, ws.renders_dir(0), orbit=True, times=(0.0, 1.5), sheet=True)+ out.gates.append(frame_gate_from_renders(ws.renders_dir(0)))+ inp = JudgeInput(spec=spec, renders=out.renders, gates=out.gates, acceptance=acceptance_from_spec(spec),+ round_index=0)+ out.judgment = self.judge_for(spec).judge(inp)+ except Exception as e: # noqa: BLE001 — recorded per cell, never kills the matrix+ out.error = f"{type(e).__name__}: {e}"+ return out+def _evaluate_frames(self, ws: Workspace, spec: Spec, out: EvalOutcome) -> EvalOutcome:"""Graphics: the judged frames + the gl_frames gate + the frame metrics, as the loop does."""from codeverse.judges.base import JudgeInputdiff --git a/harness/bench/_oneshot.py b/harness/bench/_oneshot.pyindex f919292f..3ff9c2cf 100644--- a/harness/bench/_oneshot.py+++ b/harness/bench/_oneshot.py@@ -1,10 +1,12 @@"""One-shot generation backends for ``bench/compare_backends.py``.A one-shot arm gets ONE raw generation with no harness help: the model sees the-prompt plus the *minimal* blender contract (file, frame, units, naming, no-export/camera/lights) and must answer with the complete ``src/model.py``. No-tools, no cookbook, no plan, no repair loop — the harness only builds, renders-and judges whatever comes back.+prompt plus the *minimal* contract of its language (file, frame, units, naming, no+export/camera/lights) and must answer with the complete entry file — ``src/model.py``+(blender), ``src/model.py`` + ``src/robot.urdf`` (articulated), ``src/shader.frag``+(graphics, 2026-09-07), ``src/scene.js`` (scene, 2026-09-07). No tools, no cookbook,+no plan, no repair loop, no starter library — the harness only builds, renders and+judges whatever comes back.Backends (``get_oneshot_backend``):@@ -45,7 +47,7 @@ from codeverse.agents.cli_common import is_secret_env, run_with_watchdog, tailfrom codeverse.config import get_settingsfrom codeverse.contracts.artifacts import BuildResult, GateReportfrom codeverse.contracts.chat import ChatMessage, ChatRequest-from codeverse.contracts.common import Language, Usage+from codeverse.contracts.common import ENTRY_FILE, Language, Usagefrom codeverse.contracts.spec import Specfrom codeverse.conventions import LANGUAGE_FRAME, frame_docfrom codeverse.tracks.generation import MultiFileParseError, parse_multifile@@ -54,6 +56,8 @@ from codeverse.workspace import WorkspaceMODEL_FILE = "src/model.py"URDF_FILE = "src/robot.urdf"+SHADER_FILE = ENTRY_FILE[Language.GLSL_SHADER] # src/shader.frag+SCENE_FILE = ENTRY_FILE[Language.SCENE_THREEJS] # src/scene.jsDEFAULT_TIMEOUT_S = 900.0IDLE_GRACE_S = 600.0@@ -131,9 +135,60 @@ _OUTPUT_RULE_URDF = (f"You have NO tools in this session: you cannot write filesf"=== FILE: {URDF_FILE} ===\n<xml>\n=== END FILE ===")+#: The GLSL (track graphics, language glsl_shader) minimal contract: what the harness prepends+#: and expects, condensed from codeverse/prompts/glsl_shader/contract.md — no cookbook, no+#: recipes file, no frame-metric self-check.+_GLSL_CONTRACT_BODY = """You write ONE file, `{shader_file}`: the BODY of a Shadertoy-style fragment shader (GLSL 330 core).+The harness prepends these lines itself — do NOT write them (redeclaring any is an error):+ #version 330 core · uniform float u_time · uniform vec2 u_resolution · uniform vec2 u_mouse (always 0,0)+ uniform int u_frame · uniform sampler2D u_prev (previous frame, black at frame 0) · uniform sampler2D u_noise+ (256x256 RGBA white noise) · #define iTime u_time (also iResolution iFrame iMouse iChannel0=u_prev+ iChannel1=u_noise) · out vec4 fragColor (the ONLY output).+Entry point: `void mainImage(out vec4 fragColor, in vec2 fragCoord)` (preferred) or `void main()`.+NOT available: iChannel2/3, iDate, iSampleRate, textures, images, sound, includes, files.+The harness compiles it with moderngl headless, renders 1280x720 frames at t = 0, 1, 2.5, 4 and 6 s and+judges them: the shader must compile on GLSL 330 core, animate over t, and stay readable (not black,+not blown out). Keep it under ~400 lines and cheap enough for 30 fps at 1280x720."""++_OUTPUT_RULE_GLSL = (f"You have NO tools in this session: you cannot write files, compile or render anything — "+ f"the code must appear in your reply. Reply with the COMPLETE contents of `{SHADER_FILE}` as ONE "+ f"```glsl fenced code block and nothing else (no prose before or after, no partial snippets).")++#: The scene (track scene, language scene_threejs) minimal contract: the createScene shape and the+#: import rule of codeverse/prompts/scene_threejs/contract.md — no starter library, no zones,+#: no assets, no cookbook, no gates table.+_SCENE_CONTRACT_BODY = """You write ONE file, `{scene_file}`, an ES module for three.js r182:+ export async function createScene({{ THREE, renderer, loaders }}) → {{ scene, cameras, update(t, dt) }}+Imports: only `three` and `three/addons/*` (GLTFLoader, BufferGeometryUtils, Sky, Water, EffectComposer …).+No other files, packages, CDNs, textures, images, models or network — everything is procedural geometry+and materials (MeshStandardMaterial / ShaderMaterial). Y-up, +Z front, metres, real-world scale.+The return value: `scene` is a THREE.Scene with `scene.fog` set and a background colour or sky dome, lit+by your own lights; `cameras` is 3–5 PLAIN objects `{{ name, position: [x, y, z], lookAt: [x, y, z], fov }}`+(PascalCase names; fov 35–60; the first is the establishing shot; never inside or within 0.5 m of+geometry; eye height about 1.6 m for human views); `update(t, dt)` advances the animation+deterministically and cheaply (no allocations).+The harness imports the module in headless Chrome with a WebGLRenderer (shadows on, ACES tone mapping),+awaits createScene, renders every camera at t = 0 and 1.5 s and judges the frames: readable exposure+(mean luminance ≥ 0.15, no black or blown frames), things resting on the ground, cameras framing the+content, visible motion between the two times. Under 2 M triangles and 200 draw calls (InstancedMesh+for anything repeated); createScene must resolve in under 15 s."""++_OUTPUT_RULE_SCENE = (f"You have NO tools in this session: you cannot write files, run node or render anything — "+ f"the code must appear in your reply. Reply with the COMPLETE contents of `{SCENE_FILE}` as ONE "+ f"```js fenced code block and nothing else (no prose before or after, no partial snippets).")+++#: the one file a single-file language answers with (URDF answers with two, see files_for)+_ENTRY = {Language.BLENDER: MODEL_FILE, Language.GLSL_SHADER: SHADER_FILE, Language.SCENE_THREEJS: SCENE_FILE}++def files_for(language: Language) -> list[str]:"""The files a one-shot answer must contain for ``language``."""- return [MODEL_FILE, URDF_FILE] if language is Language.URDF_BLENDER else [MODEL_FILE]+ if language is Language.URDF_BLENDER:+ return [MODEL_FILE, URDF_FILE]+ if language not in _ENTRY:+ raise ValueError(f"no one-shot contract for {language.value}: " + ", ".join(sorted(x.value for x in _ENTRY)))+ return [_ENTRY[language]]def minimal_contract(language: Language = Language.BLENDER) -> str:@@ -141,19 +196,25 @@ def minimal_contract(language: Language = Language.BLENDER) -> str:if language is Language.URDF_BLENDER:return _URDF_CONTRACT_BODY.format(model_file=MODEL_FILE, urdf_file=URDF_FILE,frame=frame_doc(LANGUAGE_FRAME["urdf_blender"]))+ if language is Language.GLSL_SHADER:+ return _GLSL_CONTRACT_BODY.format(shader_file=SHADER_FILE)+ if language is Language.SCENE_THREEJS:+ return _SCENE_CONTRACT_BODY.format(scene_file=SCENE_FILE)return _CONTRACT_BODY.format(model_file=MODEL_FILE, frame=frame_doc(LANGUAGE_FRAME["blender"]))def output_rule(language: Language = Language.BLENDER) -> str:- return _OUTPUT_RULE_URDF if language is Language.URDF_BLENDER else _OUTPUT_RULE+ return {Language.URDF_BLENDER: _OUTPUT_RULE_URDF, Language.GLSL_SHADER: _OUTPUT_RULE_GLSL,+ Language.SCENE_THREEJS: _OUTPUT_RULE_SCENE}.get(language, _OUTPUT_RULE)def oneshot_prompt(spec: Spec) -> str:"""The entire input of a one-shot arm: brief + constraints + minimal contract + output rule."""c = spec.constraints- urdf = spec.language is Language.URDF_BLENDER- lines = [(f"Model this ARTICULATED object as raw bpy link meshes plus a hand-written URDF: {spec.prompt.strip()}"- if urdf else f"Model this object in raw bpy: {spec.prompt.strip()}")]+ lead = {Language.URDF_BLENDER: "Model this ARTICULATED object as raw bpy link meshes plus a hand-written URDF",+ Language.GLSL_SHADER: "Write this as a Shadertoy-style fragment shader",+ Language.SCENE_THREEJS: "Build this scene in raw three.js"}.get(spec.language, "Model this object in raw bpy")+ lines = [f"{lead}: {spec.prompt.strip()}"]if c.dimensions_m:lines.append("Dimensions (m): " + ", ".join(f"{k}={v:g}" for k, v in c.dimensions_m.items()))if c.style:@@ -168,7 +229,8 @@ def repair_prompt(spec: Spec, previous_code: str | dict[str, str], build: BuildR"""Error-feedback retry (``oneshot+repair`` arm only): previous file(s) + the build error report."""report = format_error_report(build, lint)files = {MODEL_FILE: previous_code} if isinstance(previous_code, str) else previous_code- prev = "\n\n".join(f"PREVIOUS `{path}`:\n```{'xml' if path.endswith('.urdf') else 'python'}\n{body[:40_000]}\n```"+ fence = {".urdf": "xml", ".frag": "glsl", ".glsl": "glsl", ".js": "js"}+ prev = "\n\n".join(f"PREVIOUS `{path}`:\n```{fence.get(Path(path).suffix, 'python')}\n{body[:40_000]}\n```"for path, body in files.items())plural = "files" if len(files) > 1 else "file"return (oneshot_prompt(spec)@@ -208,16 +270,30 @@ def _strip_hallucinated_tool_xml(text: str) -> str:if not bodies:return textbody = max(bodies, key=len)- return body if "import bpy" in body else text+ return body if any(k in body for k in ("import bpy", "createScene", "mainImage", "void main")) else text-def extract_model_file(text: str) -> str:- """The python file from a one-shot answer (tolerant: fenced block / bare code / FILE envelope /- hallucinated Write-tool XML)."""- files = parse_multifile(_strip_hallucinated_tool_xml(text), expected_files=[MODEL_FILE])- code = files.get(MODEL_FILE) or next(iter(files.values()), "")+#: what a bare (unfenced) answer must contain to be read as the file at all+_BARE_MARKERS = {SCENE_FILE: ("createScene",), SHADER_FILE: ("mainImage", "void main(")}+++def extract_model_file(text: str, rel: str = MODEL_FILE) -> str:+ """The one file of a single-file answer (tolerant: fenced block / bare code / FILE envelope /+ hallucinated Write-tool XML) — ``src/model.py`` by default, the shader or the scene module+ when ``rel`` says so."""+ stripped = _strip_hallucinated_tool_xml(text)+ try:+ files = parse_multifile(stripped, expected_files=[rel])+ except MultiFileParseError:+ # a bare module body with no fence and no envelope (the tool-less CLI answered with+ # nothing but the code): accepted only when it carries the language's entry point —+ # prose never does, and the python path keeps parse_multifile's own bare-code rule+ if "```" in stripped or not any(k in stripped for k in _BARE_MARKERS.get(rel, ())):+ raise+ files = {rel: stripped.strip("\n") + "\n"}+ code = files.get(rel) or next(iter(files.values()), "")if not code.strip():- raise MultiFileParseError("empty model file in the answer")+ raise MultiFileParseError(f"empty {rel} in the answer")return code if code.endswith("\n") else code + "\n"@@ -231,7 +307,7 @@ def extract_files(text: str, language: Language = Language.BLENDER) -> dict[str,"""expected = files_for(language)if len(expected) == 1:- return {MODEL_FILE: extract_model_file(text)}+ return {expected[0]: extract_model_file(text, expected[0])}files = parse_multifile(text, expected_files=expected)missing = [f for f in expected if not (files.get(f) or "").strip()]if missing:diff --git a/harness/bench/compare_backends.py b/harness/bench/compare_backends.pyindex 6c0d5129..4c84fed4 100644--- a/harness/bench/compare_backends.py+++ b/harness/bench/compare_backends.py@@ -83,7 +83,7 @@ from bench.run_bench import ( # noqa: E402)from codeverse.config import get_settings # noqa: E402from codeverse.contracts.artifacts import RenderSet # noqa: E402-from codeverse.contracts.common import ENTRY_FILE # noqa: E402+from codeverse.contracts.common import ENTRY_FILE, Track # noqa: E402from codeverse.contracts.run import RunRecord # noqa: E402from codeverse.contracts.spec import Spec # noqa: E402from codeverse.cost import run_ledger # noqa: E402@@ -186,6 +186,11 @@ def _generate_oneshot(arm: Arm, spec: Spec, cell: Path, eval_ws: Workspace, optsdeps: CompareDeps, res: CellResult) -> None:backend = deps.oneshot_backend(arm.target)prompt = oneshot_prompt(spec)+ if spec.track is Track.SCENE:+ # the answer is ONE src/scene.js; the render host still needs the workspace scaffold+ # (package.json, the harness-owned lib the example imports). The example's own+ # scene.js is overwritten by the answer below — the model never sees any of it.+ deps.evaluator.runtime(spec.language).skeleton(eval_ws, None)max_attempts = 1 + (opts.repair_attempts if arm.kind == "oneshot+repair" else 0)for attempt in range(max_attempts):gen_dir = cell / "gen" / f"attempt{attempt}"@@ -265,6 +270,10 @@ def _run_harness(spec: Spec, cell: Path, eval_ws: Workspace, opts: CompareOptionreturn# the whole src/ tree: agents may split helpers into src/parts/*.py (the build wrapper puts src/ on sys.path)shutil.copytree(run_ws.src, eval_ws.src, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", "*.pyc"))+ # a scene's Blender heroes live in public/assets/*.glb, preloaded by src/scene.js over http:+ # without them every hero clone is a 404 and the fixed evaluation judges an empty zone+ if spec.track is Track.SCENE and (run_ws.root / "public").is_dir():+ shutil.copytree(run_ws.root / "public", eval_ws.root / "public", dirs_exist_ok=True)def _new_cell(item: BenchPrompt, arm: Arm, out: Path, opts: CompareOptions) -> tuple[Path, CellResult]:diff --git a/harness/tests/compare_bench/test_fixed_eval_language.py b/harness/tests/compare_bench/test_fixed_eval_language.pyindex ac9cd08f..10b10346 100644--- a/harness/tests/compare_bench/test_fixed_eval_language.py+++ b/harness/tests/compare_bench/test_fixed_eval_language.py@@ -77,3 +77,44 @@ def test_graphics_judge_is_the_track_rubric_with_the_photos():assert plain.rubric.name == "shader_v2" and not isinstance(plain, LikenessJudge)obj = ev.judge_for(Spec(id="o", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="x"))assert obj.rubric.name == "static_object_v1"+++def test_scene_cells_are_judged_on_their_cameras_and_orbit_frames(monkeypatch, tmp_path):+ """2026-09-07: the compare bench had no scene branch — a scene cell built (no GLB) and+ `evaluate` returned before judging. A scene is judged on render_scene's frames (authored+ cameras + orbit rig, t = 0 and 1.5 s) with the scene_frames gate on the scene rubric."""+ from types import SimpleNamespace++ from bench._fixed_eval import FixedEvaluator+ from codeverse.contracts.artifacts import BuildResult, GateReport, RenderSet, RenderView+ from codeverse.contracts.common import Track+ from codeverse.contracts.spec import Constraints, Spec+ from codeverse.workspace import Workspace++ ws = Workspace(tmp_path / "run").create()+ png = tmp_path / "f.png"+ png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 16)+ build = BuildResult(ok=True, language="scene_threejs", glb_path=None)+ ev = FixedEvaluator("fake:judge", n_samples=1)+ ev._runtimes[Language.SCENE_THREEJS] = SimpleNamespace(lint=lambda ws: GateReport(gate="lint", passed=True), build=lambda ws, timeout_s: build)+ import bench._fixed_eval as fe+ import codeverse.spatial.frame_metrics as fm+ import codeverse.spatial.render_scene as rs+ seen: dict[str, object] = {}+ monkeypatch.setattr(rs, "render_scene", lambda ws, out, **kw: (seen.__setitem__("kw", kw),+ RenderSet(views=[RenderView(name="Establishing_t0", path=str(png))], renderer="fake"))[1])+ monkeypatch.setattr(fm, "frame_gate_from_renders", lambda src: GateReport(gate="scene_frames", passed=True))++ class _J:+ def judge(self, inp):+ seen["inp"] = inp+ return SimpleNamespace(overall=0.66, passed=False)+ monkeypatch.setattr(fe.FixedEvaluator, "judge_for", lambda self, spec: (seen.__setitem__("spec", spec), _J())[1])+ spec = Spec(id="s", track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="a harbour",+ constraints=Constraints(must_have=["boats"]))+ out = ev.evaluate(ws, spec)+ assert out.error == "", out.error+ assert out.judgment.overall == 0.66+ assert seen["kw"]["orbit"] is True and tuple(seen["kw"]["times"]) == (0.0, 1.5)+ assert [g.gate for g in seen["inp"].gates] == ["lint", "scene_frames"]+ assert [a.text for a in seen["inp"].acceptance] == ["boats"]diff --git a/harness/tests/compare_bench/test_oneshot.py b/harness/tests/compare_bench/test_oneshot.pyindex 47f4944b..236b36a7 100644--- a/harness/tests/compare_bench/test_oneshot.py+++ b/harness/tests/compare_bench/test_oneshot.py@@ -13,10 +13,14 @@ if str(REPO) not in sys.path:from bench._oneshot import ( # noqa: E402MODEL_FILE,+ SCENE_FILE,+ SHADER_FILE,ApiOneShot,ClaudeOneShot,CodexOneShot,+ extract_files,extract_model_file,+ files_for,get_oneshot_backend,minimal_contract,oneshot_prompt,@@ -130,3 +134,51 @@ def test_extract_model_file_from_hallucinated_write_tool_xml():text = ('<invoke name="Write">\n<parameter name="file_path">/tmp/x/src/model.py</parameter>\n''<parameter name="content">import bpy\nprint(2)\n</parameter>\n</invoke>\n\nsyntax ok\n')assert extract_model_file(text) == "import bpy\nprint(2)\n"+++# --------------------------------------------------------------------------- scene + graphics (2026-09-07)+def _scene_spec() -> Spec:+ return Spec(id="t/harbour", track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="a fishing harbour at dusk",+ constraints=Constraints(must_have=["at least 3 boats", "lit windows"]))+++def _glsl_spec() -> Spec:+ return Spec(id="t/aurora", track=Track.GRAPHICS, language=Language.GLSL_SHADER, prompt="an aurora over snow",+ constraints=Constraints(must_have=["curtains that move"]))+++def test_scene_prompt_is_the_createscene_contract_and_nothing_of_the_harness():+ """The bare baseline for the scene track: ONE src/scene.js against the createScene shape and+ the import rule — no starter lib, no zones, no cookbook, no assets, no gates table."""+ p = oneshot_prompt(_scene_spec())+ assert p.startswith("Build this scene in raw three.js: a fishing harbour at dusk")+ assert "MUST HAVE: at least 3 boats" in p and SCENE_FILE in p and "createScene" in p+ assert "three/addons/*" in p and "scene.fog" in p and "lookAt" in p and "```js" in p+ assert "cookbook" not in p.lower() and "src/lib" not in p and "zones/" not in p and "public/assets" not in p+ assert minimal_contract(Language.SCENE_THREEJS) in p and p.rstrip().endswith("no partial snippets).")+++def test_glsl_prompt_is_the_shader_contract_and_nothing_of_the_harness():+ p = oneshot_prompt(_glsl_spec())+ assert p.startswith("Write this as a Shadertoy-style fragment shader: an aurora over snow")+ assert SHADER_FILE in p and "mainImage" in p and "u_time" in p and "#version 330 core" in p and "```glsl" in p+ assert "recipes.glsl" not in p and "cookbook" not in p.lower() and "buffer_a" not in p+ assert minimal_contract(Language.GLSL_SHADER) in p+++def test_single_file_answers_are_extracted_under_their_own_entry():+ js = "import * as THREE from 'three';\nexport async function createScene({ THREE }) { return {}; }"+ assert extract_files(f"Here you go:\n```js\n{js}\n```\n", Language.SCENE_THREEJS) == {SCENE_FILE: js + "\n"}+ glsl = "void mainImage(out vec4 o, in vec2 p) { o = vec4(p / iResolution.xy, 0.5, 1.0); }"+ assert extract_files(f"```glsl\n{glsl}\n```", Language.GLSL_SHADER) == {SHADER_FILE: glsl + "\n"}+ assert files_for(Language.SCENE_THREEJS) == [SCENE_FILE] and files_for(Language.GLSL_SHADER) == [SHADER_FILE]+ with pytest.raises(ValueError, match="no one-shot contract"):+ files_for(Language.THREEJS)+++def test_a_hallucinated_write_tool_of_a_scene_module_is_still_read():+ xml = ('<invoke name="Write"><parameter name="path">src/scene.js</parameter><parameter name="content">\n'+ "export async function createScene({ THREE }) { return { scene: new THREE.Scene(), cameras: [], update() {} }; }\n"+ "</parameter></invoke>")+ got = extract_files(xml, Language.SCENE_THREEJS)[SCENE_FILE]+ assert got.startswith("export async function createScene")