Official Codebase of 3DCodeVerse
Python
scene_probe: the draw count is gated in code (WARN > 5 000, build ERROR > 15 000) and no gate or judge reads fps
gaoypeng9b6f412760ad
diff --git a/harness/codeverse3d/contracts/artifacts.py b/harness/codeverse3d/contracts/artifacts.pyindex 59119c24..88f64cd7 100644--- a/harness/codeverse3d/contracts/artifacts.py+++ b/harness/codeverse3d/contracts/artifacts.py@@ -171,42 +171,16 @@ class RenderView(BaseModel):)-#: A renderer string that means "no hardware did this". Same words as-#: `runtime_js/gpu_launch.cjs` SOFTWARE_RE, which is what decides whether a GPU attempt-#: is trusted; kept here because `fps` is only a fact about the scene when hardware-#: measured it.-SOFTWARE_RENDERERS = ("swiftshader", "llvmpipe", "softpipe", "software", "basic render")--class RenderSet(BaseModel):views: list[RenderView] = Field(default_factory=list)contact_sheet: str | None = Field(default=None, description="one labelled grid image of all views")renderer: str = ""duration_ms: int = 0console_errors: list[str] = Field(default_factory=list, description="(scenes) JS/WebGL errors seen")- fps: float | None = None+ fps: float | None = Field(default=None, description="(scenes) measured frame rate: a record only — it swings with "+ "the machine's load and renderer, so no gate or judge reads it (D99)")out_dir: str = Field(default="", description="directory the views (+ views.json/metrics.json) were written to")- @property- def software_rendered(self) -> bool:- """True when these pixels came from a CPU rasteriser.-- Measured on eval/bench/out/scene_baseline (2026-09-05): with the box's eight GPUs at- ~100 % from other work, the GPU probe's negative verdict is cached for 20 minutes,- so cells fell back to SwiftShader one at a time and `fps` was measured on a- DIFFERENT renderer per cell — 11.5 fps on an RTX 6000 Ada for one, 5.1 / 7.1 / 2.0- on SwiftShader for the next three. A CPU number is not comparable with a GPU one- and is not a property of the scene, so nothing may gate or judge on it.- """- low = self.renderer.lower()- return any(word in low for word in SOFTWARE_RENDERERS)-- @property- def hardware_fps(self) -> float | None:- """`fps` when hardware measured it, else None — the only form worth reporting."""- return None if (self.fps is None or self.software_rendered) else self.fps--# ===================================================================== judgmentclass JudgeIssue(BaseModel):target: str = Field(description="part / zone / joint / asset / 'overall'")diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.pyindex 03844867..d46a5611 100644--- a/harness/codeverse3d/conventions.py+++ b/harness/codeverse3d/conventions.py@@ -278,6 +278,14 @@ def fmt3(vec: Sequence[float]) -> str:#: the only place an object's triangle count is enforced — no build wrapper checks it.MAX_TRIS_OBJECT = 600_000MAX_TRIS_SCENE = 3_000_000+#: Scene draw budget on the probe census's ``totals.draws`` — one per visible mesh / points /+#: line / sprite per material group, an InstancedMesh once (``host_census.mjs`` ``objectDraws``).+#: ``scene_probe`` WARNs above the first and fails the build above the second, so the repair loop+#: fixes it inside the round (D99). Tuned on 753 recorded scene rounds: median fps drops below 5+#: past ~5 000; every round past 15 000 ran at ≤ 5 fps, and only 0.4 % of pre-D93 harness rounds+#: (p99 12 348) reach it.+DRAWS_WARN_SCENE = 5_000+MAX_DRAWS_SCENE = 15_000#: Default tolerance for bbox contract checks, in meters.BBOX_TOLERANCE_M = 0.01#: "Stands on the ground": the lowest point within this of up = 0 (meters). The contract gatediff --git a/harness/codeverse3d/judges/prompt_builder.py b/harness/codeverse3d/judges/prompt_builder.pyindex e27b124d..0ed1df8f 100644--- a/harness/codeverse3d/judges/prompt_builder.py+++ b/harness/codeverse3d/judges/prompt_builder.py@@ -844,15 +844,6 @@ def view_rig_section(renders: RenderSet, montages: list[Montage], *, scene: boolbits.append(RIG_RULES["object"])if renders.console_errors:bits.append(f"PROBE: {len(renders.console_errors)} console error(s) during rendering, first: {_clip(renders.console_errors[0], 200)}")- # Only a hardware measurement is a fact about the scene; a SwiftShader number is the- # box's, and the judge has no way to know which it was handed. Rather than drop it- # silently, say what it is, so a genuinely heavy scene is still visible to a reader.- if renders.hardware_fps is not None:- bits.append(f"PROBE: measured {renders.hardware_fps:.0f} fps.")- elif renders.fps is not None:- bits.append(f"PROBE: {renders.fps:.0f} fps, but on a CPU rasteriser "- f"({_clip(renders.renderer, 60)}) — NOT a statement about this scene's cost; "- f"do not raise a performance issue from it.")bits.append("Images in send order:\n" + describe_montages(montages))return "\n".join(bits)diff --git a/harness/codeverse3d/judges/rubrics/scene_v1.yaml b/harness/codeverse3d/judges/rubrics/scene_v1.yamlindex 9d70bedc..cc9b7765 100644--- a/harness/codeverse3d/judges/rubrics/scene_v1.yaml+++ b/harness/codeverse3d/judges/rubrics/scene_v1.yaml@@ -4,8 +4,8 @@ track_hint: scenepass_threshold: 0.70description: >Rubric for a procedural 3D SCENE (a place) judged on its authored cameras plus a- fitted overview rig, at one or more animation times, with a probe digest (fps,- console/shader errors, census). The scene owns its lighting, sky and fog: grade+ fitted overview rig, at one or more animation times, with a probe digest (console/shader+ errors, census). The scene owns its lighting, sky and fog: gradethe picture it makes, and the place it depicts.extra_instructions: >@@ -18,7 +18,7 @@ extra_instructions: >different montage images: do NOT judge motion by comparing them — the harness measuresthe pixel change between the two times per camera and states it in the context; thatmeasurement decides `nothing_moves` and every "it must move" acceptance item. The probe- digest lists console/shader errors and fps measured by the harness; treat those as facts.+ digest lists console/shader errors measured by the harness; treat those as facts.A gate finding that starts with "harness rig view" describes one of the harness's owncameras, not the scene: never turn it into a defect against the scene.Use zone and asset names from the plan digest as targets.@@ -144,9 +144,9 @@ criteria:title: Technical cleanlinessdescription: >No z-fighting, no magenta/default materials, no missing faces, no visible world- edge cliff, no console or shader errors in the probe digest, acceptable fps.+ edge cliff, no console or shader errors in the probe digest.anchors:- "1.0": Clean renders, zero console/shader errors, healthy fps.+ "1.0": Clean renders, zero console/shader errors."0.7": A minor artefact or a single non-fatal warning."0.4": Visible z-fighting / missing faces / hard world edge, or a console error."0.1": Broken renders, shader failures, or the scene does not run.diff --git a/harness/codeverse3d/prompts/scene_threejs/cookbook.md b/harness/codeverse3d/prompts/scene_threejs/cookbook.mdindex a3160ed5..0f524684 100644--- a/harness/codeverse3d/prompts/scene_threejs/cookbook.md+++ b/harness/codeverse3d/prompts/scene_threejs/cookbook.md@@ -865,7 +865,7 @@ white-out). Do not build an* Anything placed > 5 × is an InstancedMesh, static one-material clutter is `mergeGeometries`.* `update` caches lists, mutates in place, allocates nothing per frame.-* `scene_probe` reports draws/tris/fps — run it before polishing. When it is slow the usual+* `scene_probe` reports draws/tris — run it before polishing. When it is slow the usualcriminals are un-instanced repeats, per-frame `traverse`, and 4096² shadow maps.## Pitfalls (symptom → cause → fix)@@ -956,7 +956,7 @@ Composition self-check on every authored frame (the judge grades exactly these):* shade is coloured (sky-tinted), not black; key and fill hues differ;* t=0 and t=1.5 are visibly different.-Then: `build` → `check_placement` (floating/sunken/interpenetration + the fix per asset) → `scene_probe` (draws/tris/fps/console) → `scene_views` (authored cameras ++Then: `build` → `check_placement` (floating/sunken/interpenetration + the fix per asset) → `scene_probe` (draws/tris/console) → `scene_views` (authored cameras +overview rig, with `camera_checks`) → `shader_probe` if you wrote GLSL → fix the worst →repeat. Look at every camera's frame AND its numbers: no black frames, no white-out, thesubject (not sky/ground) fills the establishing shot, `camera_in_geometry` false, and `check_placement`diff --git a/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md b/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.mdindex f1140fad..746a5195 100644--- a/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md+++ b/harness/codeverse3d/skills/c3d-scene-composition/references/measured-cameras.md@@ -74,7 +74,7 @@ counting as content, and its top surface becomes `ground_y` for every camera che## 5. Cheap self-check before you finish```-scene_probe -> triangles, draw calls, fps, console errors, custom-shader mesh count+scene_probe -> triangles, draws, console errors, custom-shader mesh countscene_views -> camera_checks per camera: mean_lum, modal_frac, content_frac,nearest_hit_m, eye_height_m, ground_y```diff --git a/harness/codeverse3d/spatial/probes.py b/harness/codeverse3d/spatial/probes.pyindex 188ee829..9253dd34 100644--- a/harness/codeverse3d/spatial/probes.py+++ b/harness/codeverse3d/spatial/probes.py@@ -17,7 +17,7 @@ from pydantic import BaseModel, Fieldfrom codeverse3d.config import get_settingsfrom codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity-from codeverse3d.conventions import MAX_TRIS_SCENE+from codeverse3d.conventions import DRAWS_WARN_SCENE, MAX_DRAWS_SCENE, MAX_TRIS_SCENEfrom codeverse3d.spatial.render_scene import SceneRenderError, probe_env_args, run_scene_scriptfrom codeverse3d.workspace import Workspace@@ -195,6 +195,7 @@ def _census_findings(c: dict[str, Any]) -> list[GateFinding]:if tot.get("triangles", 0) > MAX_TRIS_SCENE:out.append(_f(gate, Severity.WARN, f"{tot['triangles']:,} triangles exceeds the {MAX_TRIS_SCENE:,} budget", target="scene",hint="lower segment counts, use InstancedMesh for repeats, merge static geometry"))+ out.extend(_draw_findings(c))unnamed = [g["name"] for g in c.get("groups", []) if not g.get("named") and g.get("kind") == "content"]if unnamed:out.append(_f(gate, Severity.WARN, f"{len(unnamed)} top-level content object(s) without a name: {unnamed[:5]}", target="src/scene.js",@@ -206,6 +207,25 @@ def _census_findings(c: dict[str, Any]) -> list[GateFinding]:return out+def _draw_findings(c: dict[str, Any]) -> list[GateFinding]:+ """The scene draw budget (D99): ``totals.draws`` against ``DRAWS_WARN_SCENE`` /+ ``MAX_DRAWS_SCENE``. The count is the census's, so it is the number ``scene_probe`` shows+ and the same on every machine, camera and load — fps is not (2 961 draws measured 10.4,+ 9.6 and 1.6 fps in three rounds of one run). An ERROR fails the build, which puts it in the repair loop."""+ draws = int(c.get("totals", {}).get("draws", 0))+ if draws <= DRAWS_WARN_SCENE:+ return []+ sev, limit = (Severity.ERROR, MAX_DRAWS_SCENE) if draws > MAX_DRAWS_SCENE else (Severity.WARN, DRAWS_WARN_SCENE)+ heavy = sorted((g for g in c.get("groups", []) if g.get("draws")), key=lambda g: -g["draws"])[:3]+ where = ", ".join(f"{g['name']} {g['draws']:,}" for g in heavy)+ return [_f(PROBE_GATE, sev,+ f"{draws:,} draw calls per frame (each visible mesh is one) exceed the {limit:,} budget"+ + (f" — most in {where}" if where else "")+ + "; instance repeated geometry with InstancedMesh (lib/instancing.js instanceAsset) or merge "+ "static clutter with mergeGeometries (lib/merge.js mergeStatic)",+ target="scene", kind="draw_calls", draws=draws, limit=limit)]++def shader_report(report: dict[str, Any], *, duration_ms: int = 0) -> GateReport:"""Interpret a shader-preflight report (the ``shader_report`` block of``probe_scene.mjs --compile``) into the ``shader_preflight`` GateReport. Pure overdiff --git a/harness/codeverse3d/spatial/render_scene.py b/harness/codeverse3d/spatial/render_scene.pyindex 288b9011..1b8a62c9 100644--- a/harness/codeverse3d/spatial/render_scene.py+++ b/harness/codeverse3d/spatial/render_scene.py@@ -284,25 +284,6 @@ def _store_motion(out_dir: Path, metrics: dict[str, Any]) -> None:log.warning("could not write motion into %s: %s", out_dir / "metrics.json", e)-def perf_detail(rs: RenderSet) -> str:- """`` — 5028 draw calls, 191k triangles`` from a render's own instruments.-- The number is what makes a low-fps finding actionable: "low fps" is a mood, "5028 draw- calls" names the fix. ``""`` when the instruments are missing."""- try:- path = metrics_path_for(rs)- if path is None:- return ""- fps = (json.loads(path.read_text()).get("fps") or {})- calls, tris = fps.get("draw_calls"), fps.get("triangles")- bits = [f"{int(calls)} draw calls" if isinstance(calls, (int, float)) else "",- f"{int(tris) / 1000:.0f}k triangles" if isinstance(tris, (int, float)) else ""]- inner = ", ".join(b for b in bits if b)- return f" — {inner}" if inner else ""- except (OSError, ValueError, TypeError):- return ""--def select_judge_views(rs: RenderSet, max_n: int = JUDGE_MAX_VIEWS, *, orbit_names: Sequence[str] | None = None) -> RenderSet:"""Copy of ``rs`` with the views a judge should see (≤ ``max_n``), in priority order:authored cameras at the first time · the first two overview orbit views at that timediff --git a/harness/codeverse3d/spatial/tools.py b/harness/codeverse3d/spatial/tools.pyindex 539ace84..44b75172 100644--- a/harness/codeverse3d/spatial/tools.py+++ b/harness/codeverse3d/spatial/tools.py@@ -426,7 +426,7 @@ def shader_probe(ctx: ToolContext, args: NoArgs) -> Observation:return gate_observation(shaders if ran else probe, title="shader probe")-@tool("scene_probe", NoArgs, "Load the scene headlessly: object/material/light census, triangle count, fps, console errors.",+@tool("scene_probe", NoArgs, "Load the scene headlessly: object/material/light census, draw and triangle counts, console errors.",languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")def scene_probe(ctx: ToolContext, args: NoArgs) -> Observation:res = probe_scene(ctx.workspace)diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.pyindex 26bb13c2..fcb781aa 100644--- a/harness/codeverse3d/tracks/scene.py+++ b/harness/codeverse3d/tracks/scene.py@@ -44,7 +44,6 @@ from codeverse3d.models import get_chat_modelfrom codeverse3d.orchestrator import BudgetExceeded, TaskGroup, compact_instructionsfrom codeverse3d.prompts import renderfrom codeverse3d.spatial.frame_motion import motion_text_for-from codeverse3d.spatial.render_scene import perf_detailfrom codeverse3d.spatial.scene_placement import placement_gatefrom codeverse3d.texturing.plan import texture_pack_promptfrom codeverse3d.tracks import skills_hook@@ -120,17 +119,6 @@ class ScenePipeline:findings = [GateFinding(gate="render_console", severity=Severity.ERROR, target=_guess_target(e, ctx.plan), message=e[:300],data={"kind": "console_error"}, fix_hint="open the named module, fix the thrown error; run the build/probe tool until no console errors")for e in errs[:MAX_CONSOLE_ERRORS]]- # `hardware_fps`, not `fps`: a number measured on SwiftShader is the box's, and- # telling the agent to merge geometry because the CPU rasteriser is slow sends it- # optimising a scene that was never the problem (2026-09-05, three cells of- # scenes_v1 measured 2-7 fps on SwiftShader while a fourth measured 11.5 on an- # RTX 6000 — four different renderers, one gate threshold).- if renders.hardware_fps is not None and renders.hardware_fps < 20:- findings.append(GateFinding(gate="render_console", severity=Severity.WARN, target="overall", data={"kind": "low_fps"},- message=f"low frame rate {renders.hardware_fps:.0f} fps" + perf_detail(renders),- fix_hint="merge static geometry "- "(BufferGeometryUtils.mergeGeometries) and put anything repeated > 5x in ONE "- "InstancedMesh per material — a per-object mesh loop is what costs the frame rate"))out = [GateReport.of("render_console", findings)]try:# scene_frames: exposure / camera-in-geometry / coverage checks from metrics.jsondiff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex 449c1310..0c343b97 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -524,7 +524,9 @@ A build's OWN gate reports ride `BuildResult.gates` — scene `scene_probe` + `s(one browser boot), graphics `gl_frames` — and `steps._run_round` appends them to the round'sgates after the track's (a failed build's too: a shader compile error is what routes theshader-traps skill); before 2026-09-22 the scene's two never reached a round, and an always-empty-`scene_census` gate parsed census keys the probe had stopped writing.+`scene_census` gate parsed census keys the probe had stopped writing. `scene_probe` also holds the scene draw budget+(D99): the census's `totals.draws` WARNs past `conventions.DRAWS_WARN_SCENE` and fails the build past+`MAX_DRAWS_SCENE`, so the round's repair session gets it; no gate or judge reads fps.## 8. Texturing (derived asset pack)@@ -565,7 +567,8 @@ the since-deleted in-process `api-agent` and the since-removed pass / plateau st* Articulated: candidate selection uses the quick 4-view rig plus the sweep's pose views;mimic joints are honoured (the sweep drives independent joints only and resolvesfollowers through the chain); sweep is O(links² × poses).-* Scenes: fps is a relative cost; camera-in-geometry can miss open-back enclosures.+* Scenes: fps is a record only (machine- and load-dependent; the draw count is what is gated);+ camera-in-geometry can miss open-back enclosures.* threejs: textures are stripped on GLB export (the texture pass re-adds them as aderived pack); `userData.tick` cannot survive export.* agy exposes no per-workspace MCP, cost or served model; a killed agy session books nodiff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.mdindex cd7594a0..af0fc261 100644--- a/harness/docs/DECISIONS.md+++ b/harness/docs/DECISIONS.md@@ -550,7 +550,8 @@ Pointers: EVAL, PAPER_WRITING = `eval/docs/*.md`; COST, RUNBOOK, ARCHITECTURE, I`RenderSet.software_rendered` reads the renderer string with the words `gpu_launch.cjs` uses; thejudge prompt keeps a software number but LABELS it, and an unrecognised renderer string is neverclaimed as software. An fps comparison across cells is valid only within one backend- (`contracts/artifacts.py`, `tests/scene_gates/test_software_fps.py`).+ (`contracts/artifacts.py`, `tests/scene_gates/test_software_fps.py`). Superseded by D99: no gate or+ judge reads fps at all.* **D58 The scene texture pack is wired into the loop, behind a switch that is off (2026-09-05).**Four of the 24 judge issues over the first `scenes_v1` battery's five scored cells say the@@ -1030,6 +1031,34 @@ Pointers: EVAL, PAPER_WRITING = `eval/docs/*.md`; COST, RUNBOOK, ARCHITECTURE, Ithreshold is not stated as a geometric rule in always-on text (bbox ±0.01 m, camera 0.3/0.5 m, placement2 cm/2.5x…); construction values (weld overlap, clearances, wall thickness) and the skills' pinnedgate explanations stay.+* **D99 The scene draw budget is a census count gated in code; fps is a record only (owner, 2026-09-24).**+ The regression: D93 took "≤ 200 draw calls" / "≤ 40 per zone" / "fps ≥ 30" / "≤ 300 meshes" out of the+ scene prompts, but nothing in code enforced draws — only a `hardware_fps < 20` WARN, which never becomes a+ task. On the same scenes_v2 prompts the new tree's agents wrote 3–6x the meshes (P3 95a9820 → P4+ 93af8d6e: cliff_monastery 506 → 1 450 meshes and 69 → 4.9 fps, conservatory 311 → 1 776, canal_town+ 1 950 → 12 665; the conservatory's round 0 drew 46 567 calls at 1 fps). Decision 1: `scene_probe` gates+ the census's `totals.draws` — one per visible Mesh / Points / Line / Sprite per material group, an+ InstancedMesh once (`host_census.mjs` `objectDraws`) — the number the probe (and the `scene_probe` tool)+ reports, independent of camera, culling, GPU and load; the render's `fps.draw_calls` is one frame from one+ camera and adds culling and shadow passes (0.54 / 0.91 / 1.81x the mesh count at p5 / p50 / p95 on+ the corpus). WARN above+ `conventions.DRAWS_WARN_SCENE` = 5 000, ERROR above `MAX_DRAWS_SCENE` = 15 000; the ERROR fails the build,+ so `build_with_repair` hands it to the round's repair session with the count, the threshold, the three+ heaviest top-level groups and the fix (InstancedMesh / `mergeGeometries`, `lib/instancing.js` /+ `lib/merge.js`). Tuned on 753 recorded rendered scene rounds (~/3dcodeverse_bench_out, ~/3dcodeverse_runs;+ mesh count, which the re-probed draws match to < 1 %): log(meshes) vs log(fps) r = −0.88 (triangles −0.54);+ median fps 232 below 500 meshes, 15 at 1–2 k, 10 at 2–4 k, 4.5 at 5–7.5 k, 2 past 10 k, 0.6 past 20 k.+ Pre-D93 harness rounds (n = 255): p50 2 943, p90 6 203, p99 12 348, max 17 291 — 20 % WARN, 0.4 % (one+ 1-fps conservatory) ERROR; post-D93 (n = 218): p90 11 212, p95 20 450, max 55 990 — 6.9 % ERROR, every one+ at ≤ 4.4 fps. One-shot baselines never pass 4 761. The `render_console` fps WARN, `perf_detail`,+ `RenderSet.hardware_fps` / `software_rendered` are deleted (D57's labelling has no reader left).+ Decision 2: fps leaves the judge — no `PROBE: … fps` line, and `scene_v1` no longer asks for "acceptable /+ healthy fps" (Law 3: the VLM judges pictures; performance is gated in code, animation by the+ frame-difference metric). `RenderSet.fps` stays as a recorded measurement (and in the `scene_views` tool's+ output). `SCORING_VERSION` stays 3: it stamps the arithmetic downstream of the model, which is unchanged,+ and a stored verdict still replays; the judge INPUT changed (manifest re-blessed), so a scene judged before+ and after this commit differs by the fps line and two rubric phrases. A draw WARN is still a gate WARN in+ the judge's list, which the judge is told never makes a defect present.## Rejected / deferreddiff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.mdindex efc2432a..51c2689d 100644--- a/harness/docs/SKILLS.md+++ b/harness/docs/SKILLS.md@@ -220,7 +220,7 @@ cap and the order themselves come from `select`'s final sort and slice, pinned bleft seven `scene_frames` kinds unrouted and R19 unreachable, and any gate reword could unroutea skill. Every gate writes a `data.kind` — the lints from one vocabulary(`contracts.artifacts.LintKind`), connectivity `stray_islands` / `no_ground`, motion_direction-`wrong_direction` / `skipped`, render_console `console_error` / `low_fps` (2026-09-24) — so R9+`wrong_direction` / `skipped`, render_console `console_error` (2026-09-24), scene_probe `draw_calls` (D99) — so R9answers `lint/part_not_imported` and R13 `motion_direction/wrong_direction`, not every lint ormotion line. A finding recorded before its gate wrote one is `<gate>/untyped`, which only afamily row answers; the lint gates are one `lint` family. INFO findings are census, not defects, and have no kind — routing offdiff --git a/harness/runtime_js/lib/host_census.mjs b/harness/runtime_js/lib/host_census.mjsindex 8022a609..374e8435 100644--- a/harness/runtime_js/lib/host_census.mjs+++ b/harness/runtime_js/lib/host_census.mjs@@ -1,6 +1,6 @@/*** Deterministic scene census (page-side, pure over a THREE.Scene).- * Counts meshes / instances / lights / triangles / custom-shader materials,+ * Counts meshes / instances / draws / lights / triangles / custom-shader materials,* measures per top-level group (zone) world bboxes, classifies sky/ground* groups (shared rules: `backdrop.mjs`), computes a content bbox (sky + ground excluded) and pairwise zone* overlap statistics. Returns plain JSON.@@ -54,8 +54,19 @@ export function stampStats(points, sizes) {return { n, radius_m: +r.toFixed(2), radius_cv: +cv(radii).toFixed(3), gap_cv: +cv(gaps).toFixed(3), size_cv: +cv(sizes).toFixed(3) };}+/**+ * Draw calls one visible object submits per pass: one per material group when its material is+ * an array (three.js draws each group separately), else one. An InstancedMesh is ONE draw at+ * any instance count. Load-, camera- and GPU-independent — the `scene_probe` draw gate's count+ * (spatial/probes.py), where `fps.draw_calls` is one frame from one camera after culling.+ */+export function objectDraws(o) {+ if (!Array.isArray(o.material)) return 1;+ return Math.max(1, o.geometry?.groups?.length || 0);+}+function walkGroup(root, THREE) {- let meshes = 0, instances = 0, tris = 0, lights = 0, custom = 0;+ let meshes = 0, instances = 0, draws = 0, tris = 0, lights = 0, custom = 0;const kinds = { sky: 0, ground: 0, content: 0 };const box = new THREE.Box3(); // content onlyconst boxAll = new THREE.Box3(); // everything drawable@@ -74,6 +85,7 @@ function walkGroup(root, THREE) {if (o.isLight) lights += 1;if (!(o.isMesh || o.isPoints || o.isLine || o.isSprite)) return;const count = geometryInstances(o);+ draws += objectDraws(o);if (o.isMesh) { meshes += 1; instances += count; }if (o.isMesh) tris += triCount(o.geometry) * count;const mats = Array.isArray(o.material) ? o.material : [o.material];@@ -102,7 +114,7 @@ function walkGroup(root, THREE) {if (st) stamps.push({ name, ...st });}stamps.sort((a, b) => b.n - a.n);- return { meshes, instances, tris, lights, custom, box, boxAll, groundBox, kind, kinds, stamps: stamps.slice(0, STAMPS_PER_GROUP) };+ return { meshes, instances, draws, tris, lights, custom, box, boxAll, groundBox, kind, kinds, stamps: stamps.slice(0, STAMPS_PER_GROUP) };}function overlapStats(groups) {@@ -129,7 +141,7 @@ function overlapStats(groups) {export function sceneCensus(scene, THREE, opts = {}) {scene.updateMatrixWorld(true);const groups = [];- const totals = { meshes: 0, instances: 0, triangles: 0, lights: 0, custom_shader_meshes: 0 };+ const totals = { meshes: 0, instances: 0, draws: 0, triangles: 0, lights: 0, custom_shader_meshes: 0 };const lightTypes = {};const materials = new Set();const customMaterials = [];@@ -156,11 +168,11 @@ export function sceneCensus(scene, THREE, opts = {}) {const g = walkGroup(child, THREE);const name = child.name || `${child.type}_${groups.length}`;groups.push({- name, named: !!child.name, type: child.type, kind: g.kind, meshes: g.meshes, instances: g.instances,+ name, named: !!child.name, type: child.type, kind: g.kind, meshes: g.meshes, instances: g.instances, draws: g.draws,triangles: g.tris, lights: g.lights, custom_shader_meshes: g.custom, mesh_kinds: g.kinds,bbox: boxToJson(g.kind === 'content' ? g.box : g.boxAll), stamps: g.stamps,});- totals.meshes += g.meshes; totals.instances += g.instances; totals.triangles += g.tris; totals.lights += g.lights; totals.custom_shader_meshes += g.custom;+ totals.meshes += g.meshes; totals.instances += g.instances; totals.draws += g.draws; totals.triangles += g.tris; totals.lights += g.lights; totals.custom_shader_meshes += g.custom;if (!g.boxAll.isEmpty()) unionAll.union(g.boxAll);if (!g.box.isEmpty()) content.union(g.box);if (!g.groundBox.isEmpty()) groundAll.union(g.groundBox);diff --git a/harness/tests/judges/test_prompt_builder.py b/harness/tests/judges/test_prompt_builder.pyindex 3072e1ac..9dcd62f4 100644--- a/harness/tests/judges/test_prompt_builder.py+++ b/harness/tests/judges/test_prompt_builder.py@@ -80,10 +80,9 @@ def test_scene_rig_paragraph(judge_input, cache_dir):from codeverse3d.contracts.common import Language, Trackjudge_input.spec = judge_input.spec.model_copy(update={"track": Track.SCENE, "language": Language.SCENE_THREEJS})judge_input.renders.console_errors = ["ReferenceError: foo"]- judge_input.renders.fps = 48.0_, msgs = build_judge_messages(judge_input, load_rubric("scene_v1"), cache_dir=cache_dir)text = _parts(msgs)[0].text- assert "overview_*" in text and "console error" in text and "48 fps" in text+ assert "overview_*" in text and "console error" in textassert len(_images(msgs)) == 2 # montage + centre crop only (no ground band for scenes)diff --git a/harness/tests/scene_gates/test_draw_budget.py b/harness/tests/scene_gates/test_draw_budget.pynew file mode 100644index 00000000..668e87d3--- /dev/null+++ b/harness/tests/scene_gates/test_draw_budget.py@@ -0,0 +1,111 @@+"""The scene draw budget is a census count gated in code (D99), and the probe's harness failures stay harness failures."""++from __future__ import annotations++import pytest++from codeverse3d.contracts.artifacts import GateReport, RenderSet, Severity+from codeverse3d.conventions import DRAWS_WARN_SCENE, MAX_DRAWS_SCENE+++def _summary(draws: int) -> dict:+ groups = [{"name": "Market", "named": True, "kind": "content", "draws": draws - 10},+ {"name": "Harbour", "named": True, "kind": "content", "draws": 10}]+ return {"boot": {"ok": True, "stage": "ready"}, "update_ok": True,+ "census": {"totals": {"meshes": draws, "lights": 1, "draws": draws}, "groups": groups}}++[email protected]("draws, severity, limit", [+ (DRAWS_WARN_SCENE, None, None),+ (DRAWS_WARN_SCENE + 1, Severity.WARN, DRAWS_WARN_SCENE),+ (MAX_DRAWS_SCENE, Severity.WARN, DRAWS_WARN_SCENE),+ (MAX_DRAWS_SCENE + 1, Severity.ERROR, MAX_DRAWS_SCENE),+])+def test_the_probe_gates_the_census_draw_count(draws: int, severity: Severity | None, limit: int | None) -> None:+ """The finding states the measured count, the threshold, where the draws are and the fix."""+ from codeverse3d.spatial.probes import probe_report++ report, _ = probe_report(_summary(draws))+ hits = [f for f in report.findings if f.data.get("kind") == "draw_calls"]+ if severity is None:+ assert hits == [] and report.passed+ return+ (f,) = hits+ assert f.severity == severity and report.passed is (severity != Severity.ERROR)+ assert f.data["draws"] == draws and f.data["limit"] == limit+ for text in (f"{draws:,}", f"{limit:,}", "Market", "InstancedMesh", "mergeGeometries", "lib/merge.js", "lib/instancing.js"):+ assert text in f.message, text+++def test_a_draw_budget_error_fails_the_build_into_the_repair_report(tmp_path, monkeypatch) -> None:+ """The ERROR reaches the agent where round 0 fixes it: a failed build, whose repair report quotes it."""+ import codeverse3d.spatial.probes as probes+ from codeverse3d.contracts.common import Language+ from codeverse3d.languages.base import get_runtime+ from codeverse3d.tracks.repair import format_error_report+ from codeverse3d.workspace import Workspace++ ws = Workspace(tmp_path / "ws")+ (ws.root / "src").mkdir(parents=True, exist_ok=True)+ (ws.root / "src" / "scene.js").write_text("export function createScene() {}\n")+ draws = MAX_DRAWS_SCENE * 3++ def fake_run_probe(_ws, *, compile=False, timeout_s=None):+ probe, census = probes.probe_report(_summary(draws))+ return probe, GateReport(gate=probes.SHADER_GATE, passed=True, findings=[]), census++ monkeypatch.setattr(probes, "run_probe", fake_run_probe)+ build = get_runtime(Language.SCENE_THREEJS).build(ws)+ assert not build.ok and not build.harness_failure and build.error_type == "draw_calls"+ report = format_error_report(build, GateReport(gate="lint", passed=True, findings=[]))+ assert f"{draws:,} draw calls" in report and f"{MAX_DRAWS_SCENE:,} budget" in report and "InstancedMesh" in report+++def test_fps_is_neither_gated_nor_judged() -> None:+ """A frame rate is a record only (D99): no render gate and no judge line reads it."""+ from types import SimpleNamespace++ from codeverse3d.judges.prompt_builder import view_rig_section+ from codeverse3d.tracks.scene import ScenePipeline++ ctx = SimpleNamespace(plan=None, services=SimpleNamespace(frame_gate=lambda r: GateReport(gate="scene_frames", passed=True, findings=[])))+ slow = RenderSet(renderer="ANGLE (NVIDIA RTX 6000 Ada Generation)", fps=0.5)+ assert [f for r in ScenePipeline().post_render_gates(ctx, 0, slow) for f in r.findings] == [] # type: ignore[arg-type]+ assert "fps" not in view_rig_section(slow, [], scene=True)+++def test_a_probe_with_no_boot_record_is_a_harness_failure_not_a_verdict() -> None:+ """No `boot` in the driver summary means the driver output was lost, not that the scene failed to boot."""+ from codeverse3d.spatial.probes import probe_report++ report, census = probe_report({})+ assert not report.passed and census == {}+ assert len(report.findings) == 1+ f = report.findings[0]+ assert "no result" in f.message and "did not boot" not in f.message+ assert f.data.get("harness_failure") is True++ # a REAL boot failure still reads as one, with its stage+ real, _ = probe_report({"boot": {"ok": False, "stage": "createScene", "error": "TypeError: x"}})+ assert not real.passed and "[createScene] TypeError: x" in real.findings[0].message+++def test_a_harness_failure_finding_makes_the_probe_result_not_ok() -> None:+ """`ok` is "the tool could run"; a harness failure is an error, never an agent-facing finding."""+ from codeverse3d.contracts.artifacts import GateFinding+ from codeverse3d.spatial.probes import _result++ harness = GateReport(gate="scene_probe", passed=False, findings=[GateFinding(+ gate="scene_probe", severity=Severity.ERROR, target="src/scene.js",+ message="scene probe produced no result (driver output lost)",+ fix_hint="retry or report", data={"harness_failure": True})])+ r = _result(harness, {})+ assert r.ok is False+ assert r.errors == ["scene probe produced no result (driver output lost)"]+ assert r.findings == [], "a harness failure is never handed to the agent as a defect"++ real = GateReport(gate="scene_probe", passed=False, findings=[GateFinding(+ gate="scene_probe", severity=Severity.ERROR, target="src/scene.js",+ message="[createScene] TypeError: x is not a function", fix_hint="fix it")])+ r2 = _result(real, {"totals": {}})+ assert r2.ok is True and r2.errors == [] and len(r2.findings) == 1diff --git a/harness/tests/scene_gates/test_software_fps.py b/harness/tests/scene_gates/test_software_fps.pydeleted file mode 100644index 0ff2102f..00000000--- a/harness/tests/scene_gates/test_software_fps.py+++ /dev/null@@ -1,83 +0,0 @@-"""A frame rate measured on a CPU rasteriser is the box's, not the scene's."""--from __future__ import annotations--from codeverse3d.contracts.artifacts import RenderSet--GPU = "ANGLE (NVIDIA Corporation, NVIDIA RTX 6000 Ada Generation, Vulkan)"-CPU = "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"---def test_the_gate_does_not_fire_on_a_cpu_frame_rate() -> None:- from types import SimpleNamespace-- from codeverse3d.contracts.artifacts import GateReport- from codeverse3d.contracts.plan import BBox, CameraPlan, ScenePlan, ZonePlan- from codeverse3d.tracks.scene import ScenePipeline-- bb = BBox(center=(0, 0, 0), extents=(10, 5, 10))- plan = ScenePlan(title="t", summary="s", setting="meadow", mood="calm", bounds=bb, environment="sunny",- zones=[ZonePlan(name="Yard", description="d", bbox=bb, contents=[])], assets=[],- cameras=[CameraPlan(name="overview", position=(1, 1, 1), look_at=(0, 0, 0), fov=50, purpose="p")],- animation=[], effects=[])- # frame_gate reads metrics.json from the render dir; with no views there is none,- # so a report with no findings is the right stand-in and the events sink is a no-op- ctx = SimpleNamespace(- plan=plan, ws=None, extra={},- services=SimpleNamespace(frame_gate=lambda r: GateReport(gate='scene_frames', passed=True, findings=[])),- events=SimpleNamespace(emit=lambda *a, **k: None),- )-- def _fps_findings(renders: RenderSet) -> list[str]:- reports = ScenePipeline().post_render_gates(ctx, 0, renders) # type: ignore[arg-type]- return [f.message for r in reports for f in r.findings if "frame rate" in f.message]-- assert _fps_findings(RenderSet(renderer=CPU, fps=2.0)) == [], "SwiftShader's 2 fps is the box"- assert _fps_findings(RenderSet(renderer=GPU, fps=11.5)), "a real GPU measurement still gates"---def test_the_judge_is_told_a_cpu_number_is_not_the_scene() -> None:- """The line stays (a heavy scene must stay visible), labelled, with an instruction not to raise an issue."""- from codeverse3d.judges.prompt_builder import view_rig_section-- cpu = view_rig_section(RenderSet(renderer=CPU, fps=2.0), [], scene=True)- gpu = view_rig_section(RenderSet(renderer=GPU, fps=11.5), [], scene=True)- assert "CPU rasteriser" in cpu and "do not raise a performance issue" in cpu- assert "measured 12 fps." in gpu and "CPU rasteriser" not in gpu---def test_a_probe_with_no_boot_record_is_a_harness_failure_not_a_verdict() -> None:- """No `boot` in the driver summary means the driver output was lost, not that the scene failed to boot."""- from codeverse3d.spatial.probes import probe_report-- report, census = probe_report({})- assert not report.passed and census == {}- assert len(report.findings) == 1- f = report.findings[0]- assert "no result" in f.message and "did not boot" not in f.message- assert f.data.get("harness_failure") is True-- # a REAL boot failure still reads as one, with its stage- real, _ = probe_report({"boot": {"ok": False, "stage": "createScene", "error": "TypeError: x"}})- assert not real.passed and "[createScene] TypeError: x" in real.findings[0].message---def test_a_harness_failure_finding_makes_the_probe_result_not_ok() -> None:- """`ok` is "the tool could run"; a harness failure is an error, never an agent-facing finding."""- from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity- from codeverse3d.spatial.probes import _result-- harness = GateReport(gate="scene_probe", passed=False, findings=[GateFinding(- gate="scene_probe", severity=Severity.ERROR, target="src/scene.js",- message="scene probe produced no result (driver output lost)",- fix_hint="retry or report", data={"harness_failure": True})])- r = _result(harness, {})- assert r.ok is False- assert r.errors == ["scene probe produced no result (driver output lost)"]- assert r.findings == [], "a harness failure is never handed to the agent as a defect"-- real = GateReport(gate="scene_probe", passed=False, findings=[GateFinding(- gate="scene_probe", severity=Severity.ERROR, target="src/scene.js",- message="[createScene] TypeError: x is not a function", fix_hint="fix it")])- r2 = _result(real, {"totals": {}})- assert r2.ok is True and r2.errors == [] and len(r2.findings) == 1diff --git a/harness/tests/scene_runtime/test_census_instances.py b/harness/tests/scene_runtime/test_census_instances.pyindex f90eaba8..e73a4af2 100644--- a/harness/tests/scene_runtime/test_census_instances.py+++ b/harness/tests/scene_runtime/test_census_instances.py@@ -1,4 +1,4 @@-"""Scene budgets include shader-instanced geometry and respect hidden parents."""+"""Scene budgets include shader-instanced geometry, count draws, and respect hidden parents."""import pytestfrom codeverse3d.config import get_settings@@ -25,16 +25,21 @@ const range=sceneCensus(scene,THREE).totals;geo.setDrawRange(10,99);const empty=const points=new THREE.Points(new THREE.BoxGeometry(),new THREE.PointsMaterial());zone.add(points);const lines=new THREE.LineSegments(new THREE.BoxGeometry(),new THREE.LineBasicMaterial());zone.add(lines);const nonTriangles=sceneCensus(scene,THREE).totals.triangles;-zone.visible=false;const hidden=sceneCensus(scene,THREE).totals;const instanced=new THREE.InstancedMesh(new THREE.BoxGeometry(),new THREE.MeshBasicMaterial(),7);-instanced.count=2;-console.log(JSON.stringify({full,limited,range,empty,nonTriangles,hidden,matrix:geometryInstances(instanced)}));+instanced.count=2;zone.add(instanced);+const faces=[0,1,2,3,4,5].map(()=>new THREE.MeshBasicMaterial());zone.add(new THREE.Mesh(new THREE.BoxGeometry(),faces));+const draws=sceneCensus(scene,THREE);+zone.visible=false;const hidden=sceneCensus(scene,THREE).totals;+console.log(JSON.stringify({full,limited,range,empty,nonTriangles,hidden,matrix:geometryInstances(instanced),+ draws:draws.totals.draws,zoneDraws:draws.groups[0].draws}));""".replace("'./lib/", f"'{RUNTIME_JS}/lib/"))assert out["full"]["instances"] == 8 and out["full"]["triangles"] == 16assert out["limited"]["instances"] == 3 and out["limited"]["triangles"] == 6assert out["range"]["triangles"] == 3 and out["empty"] == 0assert out["nonTriangles"] == 0 and out["matrix"] == 2assert out["hidden"]["meshes"] == out["hidden"]["instances"] == out["hidden"]["triangles"] == 0+ # the draw gate's count (D99): cards + points + lines + the InstancedMesh once + one per face group+ assert out["draws"] == out["zoneDraws"] == 1 + 1 + 1 + 1 + 6 and out["hidden"]["draws"] == 0def test_census_matches_actual_gpu_instanced_triangle_submission():