Official Codebase of 3DCodeVerse
Python
scene: one transient vocabulary for both render paths; turn caps on every scene-stage session; the alias the stage used; inner names by family; one GLB story
gaoypenga4d1ffc77009
diff --git a/harness/codeverse/prompts/scene_threejs/contract.md b/harness/codeverse/prompts/scene_threejs/contract.mdindex 36aa4f76..978a8814 100644--- a/harness/codeverse/prompts/scene_threejs/contract.md+++ b/harness/codeverse/prompts/scene_threejs/contract.md@@ -9,7 +9,7 @@ src/zones/<snake>.js export function build<Zone>(THREE, ctx) → THREE.Groupsrc/assets/<snake>.js export function build<Asset>(THREE, opts = {}) → THREE.Group (procedural, Y-up, on y = 0)src/shaders/<snake>.js export function make<Name>Material(THREE, opts = {}) → THREE.ShaderMaterial | patched materialsrc/lib/*.js HARNESS-OWNED effect library (52 modules) — import and call, never rewrite-public/assets/<snake>.glb (optional) Blender-built assets, loaded via loaders.gltf.loadAsync('/assets/<snake>.glb')+public/assets/<snake>.glb (optional) Blender-built assets — the assembled scene.js preloads each into ctx.assets['<snake>']; zones clone it (its clips play by themselves)```The harness serves the workspace root over http (`public/assets/` is mounted at`/assets/`), imports `src/scene.js` in headless Chrome with the real `THREE`, a configureddiff --git a/harness/codeverse/prompts/scene_threejs/cookbook.md b/harness/codeverse/prompts/scene_threejs/cookbook.mdindex 3a106beb..4fae3193 100644--- a/harness/codeverse/prompts/scene_threejs/cookbook.md+++ b/harness/codeverse/prompts/scene_threejs/cookbook.md@@ -666,12 +666,12 @@ function buildLantern(THREE, opts = {}) {glow.position.y = 2.33; g.add(glow);return g;}-// GLB asset (built by src/assets/<name>.py in Blender, compiled to public/assets/<name>.glb):-async function loadAsset(loaders, name) {- const gltf = await loaders.gltf.loadAsync(`/assets/${name}.glb`);- const root = gltf.scene; root.name = name;- root.traverse(o => { if (o.isMesh) { o.castShadow = o.receiveShadow = true; } });- return root; // clone() per placement; GLB is Y-up meters already+// GLB asset (built in Blender, compiled to public/assets/<snake>.glb): the assembled scene.js+// preloads it — named, shadowed, its clips kept — into ctx.assets['<snake>']. A zone only clones:+function placeHero(ctx, key, x, z) {+ const hero = ctx.assets[key] && ctx.assets[key].clone(); // Y-up meters, base at y = 0, clips play by themselves+ if (hero) hero.position.set(x, ctx.heightAt(x, z), z);+ return hero; // null when the hero was NOT AVAILABLE — build a procedural stand-in instead}console.log('lantern ok', buildLantern(THREE).children.length);```@@ -873,8 +873,8 @@ Only if the plan asks for bloom, and the scene must still read without itscene; never near 1/far 10.9. **Sky dome black or fogged** → sky material needs `fog: false`, `side: BackSide`,`depthWrite: false`, and the tonemap/colorspace includes (see the env recipe).-10. **GLB asset invisible** → wrong URL (must be `/assets/<name>.glb`), or its pivot is not- at the base; re-export from Blender with the object on z = 0.+10. **GLB asset invisible** → the zone never cloned `ctx.assets['<snake>']` (nothing loads a GLB+ itself), or its pivot is not at the base; re-export from Blender with the object on z = 0.11. **Camera inside a tree / wall** → positions are guesses; compute from `heightAt` +known object positions, then check with `render_sheet` (the harness flagscamera-inside-geometry).diff --git a/harness/codeverse/spatial/frame_metrics.py b/harness/codeverse/spatial/frame_metrics.pyindex 2c64ba21..b34ef542 100644--- a/harness/codeverse/spatial/frame_metrics.py+++ b/harness/codeverse/spatial/frame_metrics.py@@ -243,8 +243,8 @@ def _motion_findings(rows: list[MotionRow]) -> list[GateFinding]:_UNUSED_GLB_HINT = (- "the GLB is fetched and then thrown away — either place it (add the loaded scene, or clone it: "- "`const g = await loaders.gltf.loadAsync(url); zone.add(g.scene.clone())`) or stop loading it. "+ "the GLB is preloaded by the assembled scene.js and nothing places it — clone `ctx.assets['<key>']` "+ "inside the zone the plan puts it in (every GLB under public/assets is preloaded; a zone never loads one itself). ""If a refine round replaced the asset with a procedural rebuild, DELETE the dead load: leaving it in ""makes plan.json's `assets[].kind: blender_glb` claim a Blender hero the rendered scene does not contain.")diff --git a/harness/codeverse/spatial/node.py b/harness/codeverse/spatial/node.pyindex ee0a82fb..1a5cbad8 100644--- a/harness/codeverse/spatial/node.py+++ b/harness/codeverse/spatial/node.py@@ -91,6 +91,19 @@ BROWSER_LOST_MARKERS = ("connection closed",)+#: Render failures that are the box, not the model — worth exactly one more attempt. One+#: tuple for both render paths: `render.py` had it since 2026-08-28, the scene drivers+#: retried only the browser-loss half and lost 14 renders to "Waiting failed: 60000ms+#: exceeded" under contention on 2026-09-07 (all green when re-run alone).+TRANSIENT_MARKERS = ("waiting failed", "timed out", "timeout", "produced no result", *BROWSER_LOST_MARKERS)+++def transient_failure(text: object) -> bool:+ """True when ``text`` names a failure of the box (timeouts, lost output, a dead browser)."""+ lowered = str(text).lower()+ return any(marker in lowered for marker in TRANSIENT_MARKERS)++#: Env for a retry after a browser loss: take an OWNED browser, because the shared#: one advertised in the cache is the suspect (`runtime_js/gpu_launch.cjs`).OWN_BROWSER_ENV: dict[str, str] = {"CV3D_BROWSER_REUSE": "off"}diff --git a/harness/codeverse/spatial/render.py b/harness/codeverse/spatial/render.pyindex c8480b0d..16ee8bcb 100644--- a/harness/codeverse/spatial/render.py+++ b/harness/codeverse/spatial/render.py@@ -26,12 +26,12 @@ from codeverse.conventions import OBJECT_VIEWS, ViewPresetfrom codeverse.proc import sha256_filefrom codeverse.spatial._render_common import build_sheet, out_directory, view_specsfrom codeverse.spatial.node import (- BROWSER_LOST_MARKERS,OWN_BROWSER_ENV,NodeError,browser_was_lost,run_node,runtime_js_dir,+ transient_failure,)BACKGROUNDS = ("studio", "white", "transparent")@@ -183,15 +183,13 @@ def render_glb(#: render failures that are the box, not the model: a retry is worth one more timeout.-#: The browser-loss half is shared with the scene drivers, which had no retry at all-#: until 2026-09-05 and lost four baseline cells to a marker missing from this tuple.-TRANSIENT_MARKERS = ("waiting failed", "timed out", "timeout", "produced no result", *BROWSER_LOST_MARKERS)+#: The vocabulary lives in `spatial/node.py` next to the browser-loss half, shared with+#: the scene drivers since 2026-09-07 (they used to retry only a browser loss).RETRY_PAUSE_S = 3.0def _transient(e: Exception) -> bool:- text = str(e).lower()- return any(m in text for m in TRANSIENT_MARKERS)+ return transient_failure(e)def _run_render(diff --git a/harness/codeverse/spatial/render_scene.py b/harness/codeverse/spatial/render_scene.pyindex a8dc14ae..e680631b 100644--- a/harness/codeverse/spatial/render_scene.py+++ b/harness/codeverse/spatial/render_scene.py@@ -34,6 +34,7 @@ from codeverse.spatial.node import (browser_was_lost,run_node,runtime_js_dir,+ transient_failure,)from codeverse.workspace import Workspace@@ -86,7 +87,12 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:raise SceneRenderError(f"{script} could not run: {e}") from er = attempt(env_extra)- lost_browser = _driver_failed(r) and browser_was_lost(r.summary.get("error", ""))+ err = str(r.summary.get("error", "")) if r.summary else r.stderr_tail+ lost_browser = _driver_failed(r) and browser_was_lost(err)+ # the rest of the transient vocabulary (`node.TRANSIENT_MARKERS`): a host that timed out+ # waiting for the page under contention ("Waiting failed: 60000ms exceeded") — the object+ # path retried it, this one did not, and a battery cell lost every render to it+ transient = not lost_browser and _driver_failed(r) and transient_failure(err)# Every scene driver ends with a JSON summary line (`lib/cli.finish` / `fail`), so a run# that produced none had its stdout tail dropped — `proc._ABANDONED`, which a loaded box# makes routine. That is transient and worth one more attempt; without it the empty@@ -94,14 +100,16 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:# boot" and spend the round's repair budget on a defect that was never there# (desert_canyon, bench/out/scene_baseline, 2026-09-05).lost_output = not lost_browser and not r.summary- if lost_browser or lost_output:+ if lost_browser or lost_output or transient:log.warning(- "%s %s; retrying once on an owned browser",+ "%s %s; retrying once%s",script,- f"lost its browser ({str(r.summary.get('error'))[:200]})" if lost_browser- else f"exited {r.rc} with no summary line (output lost)",+ f"lost its browser ({err[:200]})" if lost_browser+ else f"exited {r.rc} with no summary line (output lost)" if lost_output+ else f"failed transiently ({err[:200]})",+ "" if transient else " on an owned browser",)- r = attempt({**env_extra, **OWN_BROWSER_ENV})+ r = attempt(env_extra if transient else {**env_extra, **OWN_BROWSER_ENV})summary = r.summaryif _driver_failed(r):raise SceneRenderError(diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.pyindex a571f62c..65502963 100644--- a/harness/codeverse/tracks/scene.py+++ b/harness/codeverse/tracks/scene.py@@ -63,6 +63,7 @@ from codeverse.tracks.scene_assets import (MAX_ASSETS,AssetResult,asset_api_summary,+ read_dedupe_note,run_asset_stage,select_assets,single_shot_ctx,@@ -247,9 +248,12 @@ class SceneTrack(BaseTrack):ctx.extra["layouts"] = staged["layouts"] or {}assets = {k: AssetResult.model_validate(v) if isinstance(v, dict) else vfor k, v in (staged["assets"] or {}).items()}- # the merge map is a pure function of the plan, so a RESUMED run (cached asset- # stage) still tells the zones which builder+variant to call- _, alias = select_assets(list(plan.assets), MAX_ASSETS)+ # the merge map the STAGE used (its cap depends on the soft budget at the time: a+ # degraded run folded more), read back so a resumed run and the zones agree; the+ # plan-only recomputation is the fallback for a workspace without the note+ alias = read_dedupe_note(ctx.ws)+ if alias is None:+ _, alias = select_assets(list(plan.assets), MAX_ASSETS)ctx.extra["assets"] = assetsctx.extra["asset_alias"] = aliasctx.extra["asset_api"] = asset_api_summary(plan, assets, alias)@@ -343,7 +347,8 @@ class SceneTrack(BaseTrack):images=reference_images(ctx))task = self._deliver_skills(gen, "env", [task])[0]res = generate(ctx.ws, agent_id=gen.agent_id, task=task, agent=gen.agent, model=gen.model, settings=ctx.settings,- budget=ctx.budget, events=ctx.events)+ budget=ctx.budget, events=ctx.events,+ max_turns=ctx.policy.agent_max_turns, wrapup_turns=ctx.policy.agent_wrapup_turns)self._record_skills(gen, "env")ctx.ws.commit("env")return {"ok": res.ok, "files": [c.path for c in res.files_changed], "notes": res.notes}@@ -364,7 +369,8 @@ class SceneTrack(BaseTrack):def _one(batch: list[ZonePlan]) -> GenerationResult:task = skills_hook.with_inlined_skill(zone_gen, [self._zone_task(zone_gen, batch)])[0]return generate(ctx.ws, agent_id=zone_gen.agent_id, task=task, agent=zone_gen.agent, model=zone_gen.model, settings=ctx.settings,- budget=ctx.budget, events=ctx.events)+ budget=ctx.budget, events=ctx.events,+ max_turns=ctx.policy.agent_max_turns, wrapup_turns=ctx.policy.agent_wrapup_turns)results = fan_out(batches, _one, max_workers=ctx.settings.limits.max_parallel_agents, label="zones",item_name=lambda b: "+".join(z.name for z in b))@@ -437,7 +443,8 @@ class SceneTrack(BaseTrack):kind="compose", temperature=0.4, owns_entry=True, images=reference_images(ctx))task = self._deliver_skills(ctx, "compose", [task])[0]res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,- budget=ctx.budget, events=ctx.events)+ budget=ctx.budget, events=ctx.events,+ max_turns=ctx.policy.agent_max_turns, wrapup_turns=ctx.policy.agent_wrapup_turns)self._record_skills(ctx, "compose")ctx.ws.commit("compose")return {"ok": res.ok, "deterministic": False, "files": [c.path for c in res.files_changed], "notes": res.notes}diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.pyindex de87a838..068e0f9a 100644--- a/harness/codeverse/tracks/scene_assets.py+++ b/harness/codeverse/tracks/scene_assets.py@@ -140,9 +140,9 @@ def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str,cap = MAX_ASSETS if ctx.budget.soft_ok() else DEGRADED_MAX_ASSETSplanned = list(plan.assets)assets, alias = select_assets(planned, cap)+ write_dedupe_note(ctx.ws, alias)if alias:ctx.events.emit("assets.deduped", merged=alias, kept=[a.name for a in assets])- write_dedupe_note(ctx.ws, alias)built = {a.name for a in assets} | set(alias)if len(planned) > len(built):ctx.events.emit("assets.capped", n=len(planned), cap=cap, dropped=[a.name for a in planned if a.name not in built])@@ -333,7 +333,8 @@ def _generate_asset(ctx: RunContext, asset: AssetPlan, rel: str, *, language: La# zones/env); blender heroes own their whole sub-workspaceedit_only=language is Language.SCENE_THREEJS)return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,- budget=ctx.budget, events=ctx.events)+ budget=ctx.budget, events=ctx.events,+ max_turns=ctx.policy.agent_max_turns, wrapup_turns=ctx.policy.agent_wrapup_turns)def _current_files_block(ws: Workspace, files: list[str], limit: int = 24_000) -> str:@@ -624,7 +625,8 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rendeedit_only=language is Language.SCENE_THREEJS, timeout_s=asset_timeout_s(ctx, 120))restore = snapshot() if snapshot is not None else None # BEFORE the fix rewrites the filesres = generate(gen.ws, agent_id=gen.agent_id, task=task, agent=gen.agent, model=gen.model, settings=gen.settings,- budget=gen.budget, events=gen.events)+ budget=gen.budget, events=gen.events,+ max_turns=gen.policy.agent_max_turns, wrapup_turns=gen.policy.agent_wrapup_turns)if not res.ok:return resultresult.fixed = after_fix(gen) if after_fix is not None else True@@ -987,9 +989,18 @@ def variant_index(alias: dict[str, str], name: str) -> int: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})+ """Persist the merge map the stage USED: `prepare` reads it back, because the cap that+ made it (`MAX_ASSETS` or `DEGRADED_MAX_ASSETS`) depends on the soft budget at the time."""+ write_json_atomic(ws.root / "stages" / "asset_aliases.json", {"alias": alias})+++def read_dedupe_note(ws: Workspace) -> dict[str, str] | None:+ """The merge map the asset stage used, or None when no stage has run in this workspace."""+ p = ws.root / "stages" / "asset_aliases.json"+ try:+ return dict(json.loads(p.read_text()).get("alias") or {})+ except (OSError, ValueError):+ return Nonedef write_variant_shims(ws: Workspace, alias: dict[str, str], available: set[str]) -> list[str]:diff --git a/harness/runtime_js/lib/host_placement.mjs b/harness/runtime_js/lib/host_placement.mjsindex c95d62e4..9afad7d9 100644--- a/harness/runtime_js/lib/host_placement.mjs+++ b/harness/runtime_js/lib/host_placement.mjs@@ -242,7 +242,10 @@ function collectAssets(scene, indices, volumetrics, contentBox) {const inner = [];child.traverse((o) => {if (!o.visible) return;- if (o !== child && o.name && inner.length < MAX_INNER_NAMES && !inner.includes(o.name)) inner.push(o.name);+ // one slot per FAMILY (Planter_3 / Planter.003 → Planter): the by-name check matches on+ // the plan's word, and 30 numbered props must not push the hero behind them past the cap+ const family = o.name ? o.name.replace(/[_.]\d+$/, '') : '';+ if (o !== child && family && inner.length < MAX_INNER_NAMES && !inner.includes(family)) inner.push(family);if (o.isInstancedMesh) instanced += 1;else if (indices.has(o)) meshes.push(indices.get(o));else if (volumetrics.has(o)) volumetric += 1;diff --git a/harness/tests/orchestrator_tracks/test_asset_alias_note.py b/harness/tests/orchestrator_tracks/test_asset_alias_note.pynew file mode 100644index 00000000..ffcc952d--- /dev/null+++ b/harness/tests/orchestrator_tracks/test_asset_alias_note.py@@ -0,0 +1,19 @@+"""The merge map the asset stage USED is what the zones are told (2026-09-07).++`run_asset_stage` folds near-identical props under a cap that depends on the soft budget at+the time (`MAX_ASSETS` or `DEGRADED_MAX_ASSETS`); `prepare` used to recompute the map from+the plan with `MAX_ASSETS` alone, so a degraded run told the zones merged assets were+"NOT AVAILABLE" while working shims existed. The stage writes the note it used, and+`prepare` reads it back.+"""+from __future__ import annotations++from codeverse.tracks.scene_assets import read_dedupe_note, write_dedupe_note+++def test_the_note_round_trips_and_an_empty_map_is_still_a_note(tmp_ws):+ assert read_dedupe_note(tmp_ws) is None, "no stage has run"+ write_dedupe_note(tmp_ws, {"SteppingStone": "PondRock"})+ assert read_dedupe_note(tmp_ws) == {"SteppingStone": "PondRock"}+ write_dedupe_note(tmp_ws, {})+ assert read_dedupe_note(tmp_ws) == {}, "a stage that merged nothing says so (not None)"diff --git a/harness/tests/scene_runtime/test_placement_inner_families.py b/harness/tests/scene_runtime/test_placement_inner_families.pynew file mode 100644index 00000000..b1d84536--- /dev/null+++ b/harness/tests/scene_runtime/test_placement_inner_families.py@@ -0,0 +1,45 @@+"""The placement row's `inner` names count FAMILIES (2026-09-07).++D59 lists a row's named descendants (capped at `MAX_INNER_NAMES`) so the plan-contents check+can see through a wrapper group. The cap counted every distinct name, so a wrapper holding+30 `Planter_N` before the hero clone hid the hero and the check reported it missing. One+slot per family (`Planter_3` / `Planter.003` → `Planter`) keeps the hero visible and the+by-name check still matches on the plan's word.+"""+from __future__ import annotations++import pytest++from codeverse.config import get_settings+from tests.scene_runtime.conftest import needs_node, run_node_json++pytestmark = [pytest.mark.node, needs_node]++RUNTIME_JS = get_settings().runtime_js_dir()+++def test_thirty_numbered_props_before_the_hero_do_not_hide_it():+ body = f"""+import * as THREE from 'three';+import {{ sceneCensus }} from '{RUNTIME_JS}/lib/host_census.mjs';+import {{ MAX_INNER_NAMES }} from '{RUNTIME_JS}/lib/host_placement.mjs';+const solid = new THREE.MeshStandardMaterial();+const mk = (name, s, x, z) => {{ const m = new THREE.Mesh(new THREE.BoxGeometry(s, s, s), solid); m.name = name; m.position.set(x, s / 2, z); return m; }};+const hero = new THREE.Group(); hero.name = 'LoungeSofa';+for (const n of ['Seat', 'Back', 'ArmL', 'ArmR', 'Cushion.001', 'Cushion.002']) hero.add(mk(n, 0.4, hero.children.length * 0.45, 0));+const scene = new THREE.Scene();+const env = new THREE.Group(); env.name = 'Environment'; scene.add(env);+const ground = new THREE.Mesh(new THREE.PlaneGeometry(60, 60, 8, 8), solid); ground.name = 'Ground'; ground.rotation.x = -Math.PI / 2; env.add(ground);+const zone = new THREE.Group(); zone.name = 'PergolaLounge'; scene.add(zone);+const wrap = new THREE.Group(); wrap.name = 'LoungeCorner';+for (let i = 0; i < 30; i++) wrap.add(mk('Planter_' + i, 0.3, 10 + (i % 6) * 0.5, 8 + Math.floor(i / 6) * 0.5));+const c = hero.clone(); c.position.set(14, 0, 8); wrap.add(c); zone.add(wrap);+scene.updateMatrixWorld(true);+const rows = sceneCensus(scene, THREE, {{ placement: true }}).placement.assets;+const row = rows.find((a) => a.name === 'LoungeCorner');+console.log(JSON.stringify({{ cap: MAX_INNER_NAMES, inner: row.inner, hasHero: row.inner.includes('LoungeSofa') }}));+"""+ got = run_node_json(body)+ assert got["hasHero"], got+ assert "Planter" in got["inner"] and "Planter_0" not in got["inner"], got+ assert len(got["inner"]) <= got["cap"]diff --git a/harness/tests/scene_runtime/test_scene_driver_retry.py b/harness/tests/scene_runtime/test_scene_driver_retry.pyindex c5a98b33..b80d70f0 100644--- a/harness/tests/scene_runtime/test_scene_driver_retry.py+++ b/harness/tests/scene_runtime/test_scene_driver_retry.py@@ -93,3 +93,16 @@ def test_a_driver_that_answered_is_not_retried_for_a_failing_verdict(monkeypatch"error": "TypeError: x is not a function"}})])r = run_scene_script("probe_scene.mjs", ["--ws", "x"], timeout_s=10)assert r.summary["boot"]["stage"] == "createScene" and len(envs) == 1+++def test_a_transient_host_failure_is_retried_on_the_same_browser(monkeypatch):+ """`node.TRANSIENT_MARKERS` is one vocabulary for both render paths (2026-09-07): a host+ that timed out waiting for the page under contention is the box, not the scene, and it+ keeps the shared browser — only a browser LOSS takes an owned one."""+ envs = _record(monkeypatch, [+ _result(2, {"ok": False, "error": "host failed: Waiting failed: 60000ms exceeded"}),+ _result(0, {"ok": True, "n_views": 8}),+ ])+ r = run_scene_script("render_scene.mjs", ["--ws", "x"], timeout_s=10)+ assert r.summary["n_views"] == 8 and len(envs) == 2+ assert envs[1].get("CV3D_BROWSER_REUSE") is None, "a timeout is not a browser loss"