Official Codebase of 3DCodeVerse
Python
scene heroes: the same cheap-first ladder and checks a threejs asset gets; the scene in the prompt
gaoypenga50d34d44639
diff --git a/harness/codeverse/languages/scene_threejs/__init__.py b/harness/codeverse/languages/scene_threejs/__init__.pyindex 6044472e..535fcf95 100644--- a/harness/codeverse/languages/scene_threejs/__init__.py+++ b/harness/codeverse/languages/scene_threejs/__init__.py@@ -290,55 +290,15 @@ export function build(ctx) {{def _scene_for_plan(plan: ScenePlan) -> str:- zones = [(to_snake(z.name), to_pascal(z.name)) for z in plan.zones]- glbs = [to_snake(a.name) for a in plan.assets if a.kind == "blender_glb"]- zone_imports = "\n".join(f"import {{ build as build{p} }} from './zones/{s}.js';" for s, p in zones)- zone_calls = ", ".join(f"build{p}(ctx)" for _, p in zones)- cams = ",\n".join(- f" {{ name: '{to_snake(c.name)}', position: [{c.position[0]:g}, {c.position[1]:g}, {c.position[2]:g}], "- f"lookAt: [{c.look_at[0]:g}, {c.look_at[1]:g}, {c.look_at[2]:g}], fov: {c.fov:g} }}"- + (f" // {c.purpose}" if c.purpose else "")- for c in plan.cameras[:6]- )- glb_block = ""- if glbs:- preload = _glb_preload_js(- glbs, target="ctx.assets",- on_error="console.warn(`[assets] missing ${a.url} (${e && e.message}) — build it with Blender into public/assets/`);",- )- glb_block = (- "\n // Blender-built assets (public/assets/*.glb) are preloaded once, NAMED after the\n"- " // plan's asset, and cloned by the zones from ctx.assets.<key>.\n"- + preload + "\n"- )- async_kw = "async " if glbs else ""+ """The skeleton's entry point IS the assembled shape (``render_scene_js`` over the+ plan's zones, cameras and GLB assets) under the starter's contract header: the+ assemble stage overwrites this file with that very emitter, so the env / zone+ sessions author against the ``createScene`` they will actually ship with."""header = (STARTER_DIR / "scene.js").read_text().split("import * as THREE")[0]- return f'''{header}// PLAN: {plan.title} — {plan.summary.strip()}-// setting: {plan.setting.strip()} animation: {"; ".join(plan.animation) or "-"}-import * as THREE from 'three';-import {{ buildEnv, heightAt, SUN_AZIMUTH_DEG }} from './env.js';-{zone_imports}--export {async_kw}function createScene({{ THREE: T = THREE, renderer, loaders }}) {{- const scene = new THREE.Scene();- const ctx = {{ THREE, scene, renderer, loaders, heightAt, sunAzimuthDeg: SUN_AZIMUTH_DEG, assets: {{}} }};- const env = buildEnv(ctx);- ctx.env = env;-{glb_block}- const zones = [{zone_calls}];- for (const z of zones) scene.add(z);-- const cameras = [-{cams}- ];-- function update(t, dt) {{- if (env.update) env.update(t, dt);- for (const z of zones) if (z.userData.update) z.userData.update(t, dt);- }}- return {{ scene, cameras, update }};-}}-'''+ glbs = [to_snake(a.name) for a in plan.assets if a.kind == "blender_glb"]+ body = render_scene_js([to_snake(z.name) for z in plan.zones], list(plan.cameras[:6]), glbs, env_ok=True)+ return (f"{header}// PLAN: {plan.title} — {plan.summary.strip()}\n"+ f"// setting: {plan.setting.strip()} animation: {'; '.join(plan.animation) or '-'}\n" + body)def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:@@ -450,6 +410,9 @@ def _glb_preload_js(glbs: list[str], *, target: str, on_error: str, indent: str" try {"," const root = (await loaders.gltf.loadAsync(a.url)).scene;"," root.name = a.name; // a glTF root is called 'Scene' until someone names it",+ # what every procedural asset sets on its meshes; GLTFLoader leaves both false, so a+ # hero neither cast nor received a shadow in any recorded scene (8/8 GLBs, 2026-09-07)+ " root.traverse((o) => { if (o.isMesh) o.castShadow = o.receiveShadow = true; });",f" {target}[key] = root;"," } catch (e) { " + on_error + " }","}",diff --git a/harness/codeverse/prompts/tracks/scene_asset.j2 b/harness/codeverse/prompts/tracks/scene_asset.j2index 969bc0f0..69b76c48 100644--- a/harness/codeverse/prompts/tracks/scene_asset.j2+++ b/harness/codeverse/prompts/tracks/scene_asset.j2@@ -19,9 +19,25 @@ Scene: {{ spec_prompt }}{{ frame_doc }}{{ contract }}- Build the asset standing on the ground (lowest point at z=0), footprint centred on the origin,- total size as stated (±5%). Several named objects are fine; join sub-shapes that touch.-- Materials with colours (Principled BSDF base colour), roughness 0.4-0.8 for wood/stone.-- Keep it light: ≤ 40k triangles. No camera/light/render/export calls.+ total size as stated (±5%). One Blender object per plan part, named exactly as the plan says.+- Materials with colours (Principled BSDF base colour), roughness 0.4-0.8 for wood/stone; one+ material per material class (wood / iron / cloth …), never one vertex-painted mesh.+{{ detail_budget }}+- No camera/light/render/export calls.+{% if asset_files is defined and asset_files|length > 1 %}+- Files you must produce: {% for f in asset_files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}+ (the skeleton's layout: `src/model.py` is the entry, one part per `src/parts/*.py`).+{% endif %}+{% if skeleton_files is defined and skeleton_files %}++## Current files (skeleton already in src/ — keep its structure, fill in every stub)+{% for path, body in skeleton_files.items() %}+--- {{ path }} ---+```+{{ body }}+```+{% endfor %}+{% endif %}{% else %}## Contract (raw three.js ESM module){{ frame_doc }}@@ -53,7 +69,7 @@ Scene: {{ spec_prompt }}- DON'T model a flat plane with a colour where the thing has real thickness (a fence is stalks andrails, not a textured quad) — closeups are judged.- DON'T leave floating pieces: every sub-shape overlaps a neighbour by ≥ 2 mm.-- DON'T write anything but the asset file.+- DON'T write anything outside the listed file(s).{% if current_code %}## Current file (edit and return COMPLETE)diff --git a/harness/codeverse/tracks/repair.py b/harness/codeverse/tracks/repair.pyindex 52ef610e..bd397dd9 100644--- a/harness/codeverse/tracks/repair.py+++ b/harness/codeverse/tracks/repair.py@@ -155,8 +155,12 @@ def build_once(ctx: RunContext) -> tuple[BuildResult, GateReport]:def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hint: list[str] | None = None,- max_attempts: int | None = None) -> RepairOutcome:- """Lint+build; on failure run up to ``max_repair_attempts`` error-focused repairs."""+ max_attempts: int | None = None, timeout_s: int | None = None) -> RepairOutcome:+ """Lint+build; on failure run up to ``max_repair_attempts`` error-focused repairs.++ ``timeout_s`` clips every repair session (a scene asset's window is a share of the+ run, not the 1 800 s agent default: measured 2026-09-07, a 25-minute scene could+ spend 70 minutes on one hero's three repairs)."""files_hint = list(files_hint or [])max_attempts = ctx.spec.budget.max_repair_attempts if max_attempts is None else max_attemptsbuild, lint = build_once(ctx)@@ -197,7 +201,7 @@ def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hirepeats = repeats + 1 if sig == prev_sig else 0prev_sig = sigtask = make_repair_task(ctx, build, lint, round_index=round_index, attempt=attempt, repeats=repeats,- label=f"{label}_repair{attempt}", files_hint=files_hint)+ label=f"{label}_repair{attempt}", files_hint=files_hint, timeout_s=timeout_s)ctx.events.emit("repair.attempt", round=round_index, attempt=attempt, repeats=repeats, signature=sig[:200])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,@@ -215,7 +219,7 @@ def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hidef make_repair_task(ctx: RunContext, build: BuildResult, lint: GateReport, *, round_index: int, attempt: int,- repeats: int, label: str, files_hint: list[str]) -> GenerationTask:+ repeats: int, label: str, files_hint: list[str], timeout_s: int | None = None) -> GenerationTask:"""Render prompts/tracks/repair.j2 for the current strategy."""report = format_error_report(build, lint, ctx.cookbook_text, skills_hook.repair_pointers(ctx, lint))files = files_for_repair(ctx, build, lint, files_hint) if ctx.single_shot else {}@@ -226,7 +230,7 @@ def make_repair_task(ctx: RunContext, build: BuildResult, lint: GateReport, *, rtemperature = min(1.0, 0.3 + 0.25 * repeats)thinking = ("medium", "high", "high")[min(repeats, 2)]return GenerationTask(label=label, prompt=prompt, system=_repair_system(ctx), files_hint=sorted(files) or files_hint,- round=round_index, kind="repair", temperature=temperature, thinking=thinking)+ round=round_index, kind="repair", temperature=temperature, thinking=thinking, timeout_s=timeout_s)def _repair_system(ctx: RunContext) -> str:diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.pyindex 97c24eb3..92cc8bcd 100644--- a/harness/codeverse/tracks/scene_assets.py+++ b/harness/codeverse/tracks/scene_assets.py@@ -21,6 +21,7 @@ import hashlibimport jsonimport loggingimport shutil+from collections.abc import Callablefrom dataclasses import replacefrom pathlib import Pathfrom typing import Any@@ -30,14 +31,22 @@ from pydantic import BaseModel, Fieldfrom codeverse.contracts.artifacts import Judgmentfrom codeverse.contracts.common import Language, Trackfrom codeverse.contracts.plan import AssetPlan, BBox, PartPlan, ScenePlan, StaticPlan-from codeverse.contracts.spec import Spec+from codeverse.contracts.spec import Constraints, Specfrom codeverse.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snakefrom codeverse.judges.rubrics import is_degradedfrom codeverse.proc import fan_out, write_json_atomic, write_text_atomicfrom codeverse.prompts import renderfrom codeverse.tracks.common import RunContext, language_contract, load_prompt_orfrom codeverse.tracks.generation import SINGLE_SHOT_PREFIX, GenerationTask, generate, is_single_shot-from codeverse.tracks.prompting import base_prompt_context, language_system_prompt+from codeverse.tracks.planner import plan as run_planner+from codeverse.tracks.prompting import (+ base_prompt_context,+ constraints_text,+ expected_files,+ language_system_prompt,+ reference_images,+ skeleton_files,+)from codeverse.tracks.repair import build_with_repairfrom codeverse.workspace import Workspace@@ -76,6 +85,7 @@ class AssetResult(BaseModel):notes: str = ""strategy: str = Field(default="", description="single-shot | single-shot+repair | agent | escalated")judged: bool = Field(default=False, description="a non-degraded verdict was recorded in `score`")+ score_before: float | None = Field(default=None, description="the verdict the fix pass improved on (score = after)")def is_model_outage(e: BaseException) -> bool:@@ -211,6 +221,45 @@ def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> Asctx.events.emit("asset.generated", asset=asset.name, strategy="reused", ok=True, tris=chk0.tris, errors=[])return AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=chk0.size_m,strategy="reused", notes="committed module reused (import check passed)")++ def check(c: RunContext) -> AssetCheck:+ return check_threejs_asset(c, rel, pascal, expected_size_m=asset.approx_size_m)++ strategy, chk, notes = _ladder(ctx, asset, rel, language=Language.SCENE_THREEJS, files=[rel], check=check,+ timeout_s=asset_timeout_s(ctx, 120))+ if strategy == "outage":+ return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy=strategy, notes=notes)+ # a module that will not import is NOT AVAILABLE to zones; a merely imperfect one+ # (size off, still a bit plain) stays usable — we already spent a repair on it+ ok = (ctx.ws.root / rel).is_file() and not (chk is not None and chk.ran and chk.fatal)+ result = AssetResult(name=asset.name, kind=asset.kind, ok=ok, path=rel if ok else "", notes=notes, strategy=strategy,+ size_m=chk.size_m if chk and chk.size_m else None)+ ctx.events.emit("asset.generated", asset=asset.name, strategy=strategy, ok=ok, tris=(chk.tris if chk else 0),+ errors=(chk.errors[:2] if chk and not chk.ok else []))+ render_asset = getattr(ctx.runtime, "render_asset", None)+ if ok and callable(render_asset) and _judge_wanted(ctx, asset, chk, judge=judge):+ def _after_fix() -> bool:+ # a fix that breaks the module makes it NOT AVAILABLE — the zones must not import it+ c = check(ctx)+ if c.ran and c.fatal:+ result.ok, result.path = False, ""+ return c.ok++ result = _judge_and_fix(ctx, asset, result, lambda out_dir: render_asset(ctx.ws, asset.name, out_dir), files=[rel],+ language=Language.SCENE_THREEJS, after_fix=_after_fix)+ return result+++def _ladder(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, files: list[str],+ check: Callable[[RunContext], AssetCheck], timeout_s: int | None) -> tuple[str, AssetCheck | None, str]:+ """The cheap-first ladder BOTH asset kinds climb: single-shot → deterministic ``check`` →+ ONE error-feedback repair → (only then) the full agent session.++ Returns ``(strategy, last check, notes)``; ``strategy == "outage"`` means the model+ itself was down and the asset was given up before the expensive rung. The check is+ per kind — a node import for a three.js module, a Blender build + measurement for a+ hero — and the ladder is one, which is what makes the two kinds comparable.+ """sub = single_shot_ctx(ctx)chk: AssetCheck | None = Nonestrategy, notes = "", ""@@ -218,7 +267,7 @@ def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> Asif sub is not None:for attempt in range(2): # first shot + ONE error-feedback repairtry:- res = _generate_asset(sub, asset, rel, language=Language.SCENE_THREEJS, attempt=attempt,+ res = _generate_asset(sub, asset, rel, language=language, attempt=attempt, files=files,feedback=repair_feedback(chk, rel) if chk is not None else "")except Exception as e: # noqa: BLE001 — a bad answer escalates; a dead model does notfrom codeverse.orchestrator import BudgetExceeded@@ -235,7 +284,7 @@ def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> Asbreakoutage = Falsenotes = res.notes- chk = (check_threejs_asset(ctx, rel, pascal, expected_size_m=asset.approx_size_m) if res.ok+ chk = (check(sub) if res.okelse AssetCheck(ok=False, ran=True, fatal=True, errors=[f"no file was written ({res.notes or 'empty answer'})"]))if chk.ok:strategy = "single-shot" if attempt == 0 else "single-shot+repair"@@ -247,37 +296,26 @@ def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As# storm budget waiting: a full agent session is ten times the money and the same wall.# Give the asset up cheaply — the zones read "NOT AVAILABLE" and build around it.ctx.events.emit("asset.skipped_outage", asset=asset.name, errors=(chk.errors[:2] if chk else []))- return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy="outage",- notes="generator unavailable (model outage); asset skipped")+ return "outage", chk, "generator unavailable (model outage); asset skipped"if not strategy: # no chat model, or single-shot failed twice → the full agent session- res = _generate_asset(ctx, asset, rel, language=Language.SCENE_THREEJS, attempt=0,- timeout_s=asset_timeout_s(ctx, 120))+ res = _generate_asset(ctx, asset, rel, language=language, attempt=0, files=files, timeout_s=timeout_s)notes = res.notesstrategy = "escalated" if chk is not None else "agent"- chk = check_threejs_asset(ctx, rel, pascal, expected_size_m=asset.approx_size_m) if res.ok else chk- # a module that will not import is NOT AVAILABLE to zones; a merely imperfect one- # (size off, still a bit plain) stays usable — we already spent a repair on it- ok = (ctx.ws.root / rel).is_file() and not (chk is not None and chk.ran and chk.fatal)- result = AssetResult(name=asset.name, kind=asset.kind, ok=ok, path=rel if ok else "", notes=notes, strategy=strategy,- size_m=chk.size_m if chk and chk.size_m else None)- ctx.events.emit("asset.generated", asset=asset.name, strategy=strategy, ok=ok, tris=(chk.tris if chk else 0),- errors=(chk.errors[:2] if chk and not chk.ok else []))- render_asset = getattr(ctx.runtime, "render_asset", None)- if ok and callable(render_asset) and _judge_wanted(ctx, asset, chk, judge=judge):- result = _judge_and_fix(ctx, asset, result, lambda out_dir: render_asset(ctx.ws, asset.name, out_dir), files=[rel],- language=Language.SCENE_THREEJS)- return result+ chk = check(ctx) if res.ok else chk+ return strategy, chk, notesdef _generate_asset(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, attempt: int,- feedback: str = "", timeout_s: int | None = None) -> Any:+ feedback: str = "", timeout_s: int | None = None, files: list[str] | None = None) -> Any:+ files = list(files or [rel])label = f"asset_{to_snake(asset.name)}" + ("_retry" if attempt else "")- prompt = _asset_prompt(ctx, asset, rel, language=language)+ prompt = _asset_prompt(ctx, asset, rel, language=language, files=files)if feedback:- prompt = prompt + "\n\n" + feedback + "\n## Current file (rewrite it COMPLETELY)\n```\n" + _read(ctx.ws, rel, 24_000) + "\n```\n"+ prompt = prompt + "\n\n" + feedback + _current_files_block(ctx.ws, files)task = GenerationTask(label=label, prompt=prompt,system=_asset_system(ctx, language),- files_hint=[rel], round=attempt, kind="asset", temperature=0.5, timeout_s=timeout_s,+ files_hint=files, round=attempt, kind="asset", temperature=0.5, timeout_s=timeout_s,+ images=reference_images(ctx),# threejs assets share the scene workspace (a stray write would hit# zones/env); blender heroes own their whole sub-workspaceedit_only=language is Language.SCENE_THREEJS)@@ -285,9 +323,35 @@ def _generate_asset(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Labudget=ctx.budget, events=ctx.events)+def _current_files_block(ws: Workspace, files: list[str], limit: int = 24_000) -> str:+ """The file(s) the ONE feedback repair rewrites, inlined — a hero has parts, not one file."""+ out = ["## Current file(s) (rewrite COMPLETELY)"]+ for f in files:+ body = _read(ws, f, limit)+ if body:+ out.append(f"--- {f} ---\n```\n{body}\n```")+ return "\n".join(out) + "\n"++# ----------------------------------------------------------------------------- blender asset (hero)+#: a hero may spend more triangles than an instanced prop (the number the prompt states)+HERO_MAX_TRIS = 40_000+HERO_ENTRY = "src/model.py"++def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:- """Sub-workspace → Blender runtime → GLB → public/assets/<snake>.glb."""+ """Sub-workspace → the static planner's part list → the SAME ladder a threejs asset+ climbs → the GLB checked like a module → ``public/assets/<snake>.glb``.++ Until 2026-09-07 a hero got a one-part plan, a full agent session first, and no check+ of the GLB it produced. Measured over the 18 recorded heroes (bench/out, 2026-08-25 →+ 09-05): 15 first sessions killed at the asset timeout (booked at $0 — a killed CLI+ reports no usage), 12 GLBs one joined mesh with vertex paint (the one-part plan plus+ the Blender contract's "one object per plan part" leave no other way to colour it, so+ wood and iron share one roughness), median asset_v1 0.57 with 2 of 18 passing, and+ every fix prompt reading "Style of the whole scene: (none)" because the sub-spec's+ prompt IS the asset sheet.+ """snake = to_snake(asset.name)# committed-child reuse (review-3 S2), blender twin: a GLB only exists at this# path when a previous session finished the build+copy; a measurable one is done.@@ -297,51 +361,118 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> Asctx.events.emit("asset.generated", asset=asset.name, strategy="reused", ok=True, tris=0, errors=[])return AssetResult(name=asset.name, kind=asset.kind, ok=True, path=asset_file(asset), size_m=size,strategy="reused", notes="committed GLB reused")+ w, h, d = asset.approx_size_msub_ws = Workspace(ctx.ws.root / "_assets" / snake).create()runtime = ctx.services.runtime(Language.BLENDER)+ # the sub-spec IS the asset sheet (the static machinery — planner, contract gate, tools —+ # reads it); the SCENE's brief and style travel in `extra` for the asset promptssub_spec = Spec(id=f"{ctx.spec.id}-asset-{snake}", track=Track.STATIC_OBJECT, language=Language.BLENDER,- prompt=asset.description, budget=ctx.spec.budget, backends=ctx.spec.backends)- sub_plan = asset_plan(asset)+ prompt=asset.description, references=list(ctx.spec.references),+ constraints=Constraints(style=ctx.spec.constraints.style,+ dimensions_m={"width": w, "height": h, "depth": d}),+ budget=ctx.spec.budget, backends=ctx.spec.backends)sub_ws.write_json(sub_ws.spec_path, sub_spec)- sub_ws.write_json(sub_ws.plan_path, sub_plan)- sub = replace(ctx, spec=sub_spec, ws=sub_ws, runtime=runtime, plan=sub_plan, track=Track.STATIC_OBJECT,+ sub = replace(ctx, spec=sub_spec, ws=sub_ws, runtime=runtime, plan=None, track=Track.STATIC_OBJECT,contract_text=language_contract(Language.BLENDER, runtime), cookbook_rel="blender/cookbook.md",- cookbook_text=load_prompt_or("blender/cookbook.md", ""), extra={})- runtime.skeleton(sub_ws, sub_plan)- sub_ws.commit("skeleton")+ cookbook_text=load_prompt_or("blender/cookbook.md", ""),+ tool_cards=ctx.services.tool_cards(Track.STATIC_OBJECT.value, Language.BLENDER.value),+ extra={"scene_brief": ctx.spec.prompt, "scene_style": constraints_text(ctx.spec)})+ sub.plan = hero_plan(sub, asset)+ if not (sub_ws.root / HERO_ENTRY).is_file(): # a re-entry keeps the previous session's work+ runtime.skeleton(sub_ws, sub.plan)+ sub_ws.commit("skeleton")if not ctx.single_shot:ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=sub.contract_text, cookbook_rel=sub.cookbook_rel,spatial_tools=True)- res = _generate_asset(sub, asset, "src/model.py", language=Language.BLENDER, attempt=0,- timeout_s=asset_timeout_s(ctx, 180))- if not res.ok:- return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy="agent", notes=f"generation failed: {res.notes}")- sub_ws.commit("asset generated")- outcome = build_with_repair(sub, round_index=0, label=f"asset_{snake}", files_hint=["src/model.py"])- if not outcome.build.ok or not outcome.build.glb_path:- return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy="agent",- notes=f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")+ files = expected_files(sub)+ timeout_s = asset_timeout_s(ctx, 180)+ label = f"asset_{snake}"++ def check(c: RunContext) -> AssetCheck:+ return _blender_check(c, asset, files, label=label, timeout_s=timeout_s)++ strategy, chk, notes = _ladder(sub, asset, HERO_ENTRY, language=Language.BLENDER, files=files, check=check,+ timeout_s=timeout_s)+ if strategy == "outage":+ return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy=strategy, notes=notes)+ ok = chk is not None and bool(chk.glb) and not chk.fatal+ ctx.events.emit("asset.generated", asset=asset.name, strategy=strategy, ok=ok, tris=(chk.tris if chk else 0),+ errors=(chk.errors[:2] if chk and not chk.ok else []))+ if not ok:+ why = "; ".join(chk.errors[:2]) if chk and chk.errors else (notes or "no build")+ return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy=strategy, notes=f"build failed: {why}"[:300])+ sub_ws.commit("asset built")rel = asset_file(asset)- dest = _copy_glb(ctx.ws, Path(outcome.build.glb_path), rel)- size = _measure_size(ctx, dest)- result = AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=size, strategy="agent")- if _judge_wanted(ctx, asset, None, judge=judge):+ dest = _copy_glb(ctx.ws, Path(chk.glb), rel)+ result = AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=chk.size_m, strategy=strategy, notes=notes)+ if _judge_wanted(ctx, asset, chk, judge=judge):def _render(out_dir: Path):return ctx.services.render_object(dest, out_dir, views=OBJECT_VIEWS_QUICK, width=512, height=512)def _after_fix() -> bool:- oc = build_with_repair(sub, round_index=1, label=f"asset_{snake}_fix", files_hint=["src/model.py"])- if oc.build.ok and oc.build.glb_path:- _copy_glb(ctx.ws, Path(oc.build.glb_path), rel)- return True- return False-- result = _judge_and_fix(sub, asset, result, _render, files=["src/model.py"], language=Language.BLENDER,- after_fix=_after_fix, parent_events=ctx.events)- result.size_m = _measure_size(ctx, dest) or size+ oc = build_with_repair(sub, round_index=1, label=f"{label}_fix", files_hint=files, max_attempts=1,+ timeout_s=timeout_s)+ if not (oc.build.ok and oc.build.glb_path):+ return False+ _copy_glb(ctx.ws, Path(oc.build.glb_path), rel)+ sub_ws.commit("asset fix")+ result.size_m = _measure_size(ctx, dest) or result.size_m+ return True++ result = _judge_and_fix(sub, asset, result, _render, files=files, language=Language.BLENDER, after_fix=_after_fix)return result+def hero_plan(sub: RunContext, asset: AssetPlan) -> StaticPlan:+ """The static-object planner's part list for a hero, or the one-part sheet when it fails.++ One planner call, the hero's own ``plan.json``: the part names the Blender contract+ demands, per-part bboxes, ``style_notes`` and an acceptance list — what a static_object+ run gets, from the code that gives it to them.+ """+ from codeverse.tracks.static_object import StaticObjectTrack++ track = StaticObjectTrack(services=sub.services, settings=sub.settings)+ try:+ plan = run_planner(sub.spec, sub.spec.backends.planner, StaticPlan, sub.ws, events=sub.events,+ budget=sub.budget, runtime=sub.runtime, **track._plan_kwargs(sub.spec))+ except Exception as e: # noqa: BLE001 — PlanningError / outage: the sheet still says what the prop is+ from codeverse.orchestrator import BudgetExceeded++ if isinstance(e, BudgetExceeded):+ raise+ log.warning("hero planner failed for %s, using the one-part sheet: %s", asset.name, e)+ sub.events.emit("asset.plan_failed", asset=asset.name, error=f"{type(e).__name__}: {e}"[:300])+ plan = asset_plan(asset)+ sub.ws.write_json(sub.ws.plan_path, plan)+ return plan+ sub.events.emit("asset.planned", asset=asset.name, n_parts=len(plan.parts))+ return plan+++def _blender_check(ctx: RunContext, asset: AssetPlan, files: list[str], *, label: str, timeout_s: int) -> AssetCheck:+ """Build the hero — the agent path gets ONE error-focused repair session, the single-shot+ path none (its repair is the ladder's feedback rewrite) — then the soft findings a+ threejs module gets, from one measurement of the GLB."""+ outcome = build_with_repair(ctx, round_index=0, label=label, files_hint=files,+ max_attempts=0 if ctx.single_shot else 1, timeout_s=timeout_s)+ b = outcome.build+ if not b.ok or not b.glb_path:+ errors = [f"{b.error_type}: {b.error_message}"[:300] if b.error_message else "the build produced no GLB"]+ errors += [f"{f.target or 'lint'}: {f.message}"[:200] for f in outcome.lint.errors][:3]+ return AssetCheck(ok=False, ran=True, fatal=True, errors=errors)+ chk = AssetCheck(ok=True, ran=True, glb=str(b.glb_path))+ try:+ m = ctx.services.measure(Path(b.glb_path))+ except Exception as e: # noqa: BLE001 — a GLB that cannot be measured is still a GLB+ chk.warnings.append(f"measure unavailable: {type(e).__name__}")+ return chk+ chk.size_m = (round(m.extents[0], 3), round(m.extents[1], 3), round(m.extents[2], 3))+ chk.min_y, chk.tris, chk.meshes, chk.materials = round(m.bbox_min[1], 3), m.tri_count, m.n_meshes, m.materials+ _soft_findings(chk, asset.approx_size_m, max_tris=HERO_MAX_TRIS)+ return chk++def asset_plan(asset: AssetPlan) -> StaticPlan:"""A one-part StaticPlan for the asset in Blender's Z-up frame (scene sizes are Y-up w×h×d)."""w, h, d = asset.approx_size_m@@ -388,52 +519,70 @@ def _volume_fraction(ctx: RunContext, asset: AssetPlan) -> float:def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, render_fn: Any, *, files: list[str],- language: Language, after_fix: Any | None = None, parent_events: Any | None = None) -> AssetResult:- """Quick-sheet judge with asset_v1 (n_samples=1, cached renders); ONE fix pass when below threshold."""+ language: Language, after_fix: Callable[[], bool] | None = None) -> AssetResult:+ """Quick-sheet judge with asset_v1 (n_samples=1); ONE fix pass when below threshold,+ then the fix is checked (``after_fix``) and JUDGED AGAIN — ``score`` describes the+ asset that ships, ``score_before`` the one that was fixed."""from codeverse.judges.base import JudgeInput- events = parent_events or ctx.events+ events = ctx.eventstry:judge = ctx.services.judge(ASSET_RUBRIC, ctx.spec.backends.judge, n_samples=1)except Exception as e: # noqa: BLE001 — asset judging is optional polishevents.emit("asset.judge_unavailable", asset=asset.name, error=str(e))return resultout_dir = ctx.ws.renders_dir(0) / "assets" / to_snake(asset.name)- out_dir.mkdir(parents=True, exist_ok=True)- try:- renders = render_fn(out_dir)- verdict: Judgment = judge.judge(JudgeInput(spec=ctx.spec, renders=renders, round_index=0,- plan_summary=f"{asset.name}: {asset.description}",- extra_context=f"Expected size ≈ {asset.approx_size_m} m (w×h×d)."))- except Exception as e: # noqa: BLE001- events.emit("asset.judge_failed", asset=asset.name, error=f"{type(e).__name__}: {e}")- return result- # book the money non-enforcing like every other judge site (steps.py, candidates.py):- # the verdict is already paid for, and raising here would discard it. The stage- # boundary enforces the ceiling.- ctx.budget.add(verdict.usage, stage="judge")- if is_degraded(verdict):- # a degraded verdict is no verdict: score stays None and `judged` False, and the- # fix pass is skipped (its improvement_plan is empty by construction).- events.emit("asset.judge_degraded", asset=asset.name)++ def _verdict(round_index: int) -> Judgment | None:+ d = out_dir if round_index == 0 else out_dir.with_name(out_dir.name + "_fix")+ d.mkdir(parents=True, exist_ok=True)+ try:+ renders = render_fn(d)+ verdict: Judgment = judge.judge(JudgeInput(spec=ctx.spec, renders=renders, round_index=round_index,+ plan_summary=f"{asset.name}: {asset.description}",+ extra_context=f"Expected size ≈ {asset.approx_size_m} m (w×h×d)."))+ except Exception as e: # noqa: BLE001+ events.emit("asset.judge_failed", asset=asset.name, error=f"{type(e).__name__}: {e}")+ return None+ # book the money non-enforcing like every other judge site (steps.py, candidates.py):+ # the verdict is already paid for, and raising here would discard it. The stage+ # boundary enforces the ceiling.+ ctx.budget.add(verdict.usage, stage="judge")+ write_json_atomic(d / "judge.json", verdict.model_dump(mode="json")) # replayable, like a round's judge/rNN.json+ if is_degraded(verdict):+ # a degraded verdict is no verdict: score stays None and `judged` False, and the+ # fix pass is skipped (its improvement_plan is empty by construction).+ events.emit("asset.judge_degraded", asset=asset.name)+ return None+ events.emit("asset.judged", asset=asset.name, round=round_index, score=round(verdict.overall, 3), passed=verdict.passed)+ return verdict++ verdict = _verdict(0)+ if verdict is None:return resultresult.score = verdict.overallresult.judged = True- events.emit("asset.judged", asset=asset.name, score=round(verdict.overall, 3), passed=verdict.passed)if verdict.passed or not verdict.improvement_plan:return resultinstructions = [f"- {i.target}: {i.instruction}" for i in verdict.improvement_plan[:4]]+ current = "\n\n".join(f"--- {f} ---\n{_read(ctx.ws, f)}" for f in files if _read(ctx.ws, f)) if ctx.single_shot else ""prompt = render("tracks/scene_asset.j2", **base_prompt_context(ctx, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description,- asset_size=asset.approx_size_m, asset_file=files[0], asset_language=language.value, fix_instructions=instructions,- current_code=_read(ctx.ws, files[0]) if ctx.single_shot else ""))- task = GenerationTask(label=f"asset_{to_snake(asset.name)}_fix", prompt=prompt, files_hint=files, round=1, kind="asset_fix",- temperature=0.4, edit_only=language is Language.SCENE_THREEJS,- timeout_s=asset_timeout_s(ctx, 120))+ asset_size=asset.approx_size_m, asset_file=files[0], asset_files=files, asset_language=language.value,+ fix_instructions=instructions, current_code=current, skeleton_files={}, **_scene_context(ctx)))+ task = GenerationTask(label=f"asset_{to_snake(asset.name)}_fix", prompt=prompt, system=_asset_system(ctx, language),+ files_hint=files, round=1, kind="asset_fix", temperature=0.4,+ edit_only=language is Language.SCENE_THREEJS, timeout_s=asset_timeout_s(ctx, 120))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)- if res.ok:- result.fixed = after_fix() if after_fix is not None else True+ if not res.ok:+ return result+ result.fixed = after_fix() if after_fix is not None else True+ if not result.fixed:+ return result+ again = _verdict(1)+ if again is not None:+ result.score_before, result.score = result.score, again.overallreturn result@@ -455,10 +604,25 @@ def _asset_system(ctx: RunContext, language: Language) -> str:return language_system_prompt(Language.BLENDER, role="asset", tools=not is_single_shot(ctx.agent_id))-def _asset_prompt(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language) -> str:+def _scene_context(ctx: RunContext) -> dict[str, Any]:+ """The SCENE's brief and style for an asset prompt, whichever spec ``ctx`` carries.++ A blender hero runs in a sub-context whose spec IS the asset sheet (the static machinery+ needs that), so ``spec_prompt`` would render the asset description as the scene. Every+ recorded hero fix prompt (18, 2026-08-25 → 09-05) read "Style of the whole scene: (none)".+ """+ brief = ctx.extra.get("scene_brief")+ return {"spec_prompt": brief, "constraints": ctx.extra.get("scene_style") or "(none)"} if brief else {}+++def _asset_prompt(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, files: list[str] | None = None) -> str:+ files = list(files or [rel])prompt = render("tracks/scene_asset.j2", **base_prompt_context(ctx, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description, asset_size=asset.approx_size_m,- asset_file=rel, asset_language=language.value, fix_instructions=[], current_code=""))+ asset_file=rel, asset_files=files, asset_language=language.value, fix_instructions=[], current_code="",+ # a single-shot hero has to see the multi-file skeleton it is filling in, like a static object+ skeleton_files=skeleton_files(ctx) if (ctx.single_shot and len(files) > 1) else {},+ **_scene_context(ctx)))ctx.record_prompt("scene_asset", prompt)return prompt@@ -541,6 +705,7 @@ class AssetCheck(BaseModel):tris: int = 0meshes: int = 0materials: int = 0+ glb: str = Field(default="", description="the built GLB (blender heroes), '' for a module")def report(self, limit: int = 6) -> str:return "\n".join(f"- {e}" for e in (self.errors + self.warnings)[:limit])@@ -638,14 +803,14 @@ def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: flreturn chk-def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None) -> None:+def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None, *, max_tris: int = ASSET_MAX_TRIS) -> None:"""Findings that make the asset WRONG but not broken → errors worth one repair."""if not chk.ok:returnif chk.min_y is not None and chk.min_y < -0.02:chk.errors.append(f"the group sinks {abs(chk.min_y):.2f} m below y=0 — its lowest point must sit at y=0")- if chk.tris > ASSET_MAX_TRIS:- chk.errors.append(f"{chk.tris} triangles exceeds the {ASSET_MAX_TRIS} budget per asset — lower the segment counts")+ if chk.tris > max_tris:+ chk.errors.append(f"{chk.tris} triangles exceeds the {max_tris} budget per asset — lower the segment counts")if chk.meshes == 1 and chk.materials <= 1 and chk.tris < 200:chk.errors.append("the asset is still a single low-poly box (one mesh, one material): build it from several ""parts with distinct materials so it reads as the described object")