Skip to content

Official Codebase of 3DCodeVerse

Python

scene_blender builds in Blender and is gated by the unchanged JS census on a harness-written census GLB (D102)

gaoypengc17c1dacdfa6
diff --git a/harness/codeverse3d/addons/dataset/captions.py b/harness/codeverse3d/addons/dataset/captions.py
index 191e90a8..b3c2c595 100644
--- a/harness/codeverse3d/addons/dataset/captions.py
+++ b/harness/codeverse3d/addons/dataset/captions.py
@@ -47,6 +47,7 @@ LANGUAGE_PHRASE: dict[Language, tuple[str, str]] = {
Language.THREEJS: ("a Three.js module", "three.js"),
Language.URDF_BLENDER: ("a URDF model with Blender-Python-built link meshes", "urdf"),
Language.SCENE_THREEJS: ("a Three.js scene", "three.js"),
+ Language.SCENE_BLENDER: ("a Blender Python scene", "blender"),
Language.GLSL_SHADER: ("a GLSL fragment shader", "glsl"),
Language.OPENGL_PYTHON: ("an OpenGL Python program", "opengl"),
}
diff --git a/harness/codeverse3d/contracts/common.py b/harness/codeverse3d/contracts/common.py
index 86492e52..d11266c3 100644
--- a/harness/codeverse3d/contracts/common.py
+++ b/harness/codeverse3d/contracts/common.py
@@ -28,6 +28,7 @@ class Language(StrEnum):
THREEJS = "threejs" # procedural three.js (ESM) → GLB via GLTFExporter
URDF_BLENDER = "urdf_blender" # bpy link meshes + hand-written URDF
SCENE_THREEJS = "scene_threejs" # multi-file three.js scene (+GLSL, +GLB assets)
+ SCENE_BLENDER = "scene_blender" # multi-file bpy scene (+GLB heroes), rendered by Blender
GLSL_SHADER = "glsl_shader" # Shadertoy-style fragment shader (GLSL 330/ES 3.0), rendered by moderngl
OPENGL_PYTHON = "opengl_python" # raw OpenGL via moderngl + GLSL (multi-pass, geometry, FBOs)
@@ -36,7 +37,7 @@ class Language(StrEnum):
TRACK_LANGUAGES: dict[Track, tuple[Language, ...]] = {
Track.STATIC_OBJECT: (Language.BLENDER, Language.CADQUERY, Language.THREEJS),
Track.ARTICULATED_OBJECT: (Language.URDF_BLENDER,),
- Track.SCENE: (Language.SCENE_THREEJS,),
+ Track.SCENE: (Language.SCENE_THREEJS, Language.SCENE_BLENDER),
Track.GRAPHICS: (Language.GLSL_SHADER, Language.OPENGL_PYTHON),
}
@@ -74,6 +75,7 @@ ENTRY_FILE: dict[Language, str] = {
Language.URDF_BLENDER: "src/model.py",
Language.THREEJS: "src/object.js",
Language.SCENE_THREEJS: "src/scene.js",
+ Language.SCENE_BLENDER: "src/scene.py",
Language.GLSL_SHADER: "src/shader.frag",
Language.OPENGL_PYTHON: "src/program.py",
}
@@ -90,6 +92,8 @@ HARNESS_OWNED_SRC: dict[Language, tuple[str, ...]] = {
Language.GLSL_SHADER: ("src/recipes.glsl",),
# the effect library (D51): the agent imports and calls it, never rewrites it.
Language.SCENE_THREEJS: ("src/lib/",),
+ # the small bpy library (DESIGN phase 4, D51 extended): same rule, same directory
+ Language.SCENE_BLENDER: ("src/lib/",),
}
@@ -107,6 +111,7 @@ LANGUAGE_LABEL: dict[Language, str] = {
Language.URDF_BLENDER: "URDF + Blender Python",
Language.THREEJS: "Three.js (ESM)",
Language.SCENE_THREEJS: "Three.js scene (multi-file ESM + GLSL)",
+ Language.SCENE_BLENDER: "Blender scene (multi-file bpy)",
Language.GLSL_SHADER: "GLSL fragment shader",
Language.OPENGL_PYTHON: "OpenGL (moderngl Python + GLSL)",
}
diff --git a/harness/codeverse3d/contracts/plan.py b/harness/codeverse3d/contracts/plan.py
index 42ab4495..da4d7678 100644
--- a/harness/codeverse3d/contracts/plan.py
+++ b/harness/codeverse3d/contracts/plan.py
@@ -552,10 +552,23 @@ class ZonePlan(BaseModel):
contents: list[str] = Field(default_factory=list, description="asset names placed in this zone")
+#: the asset kinds each scene language plans (D5): ``bpy`` = a procedural module of a Blender
+#: scene (``src/assets/<snake>.py``), ``threejs`` its three.js twin, ``blender_glb`` a hero built as
+#: an object and shipped as a GLB (both languages)
+SCENE_ASSET_KINDS: dict[str, tuple[str, ...]] = {
+ "scene_threejs": ("threejs", "blender_glb"),
+ "scene_blender": ("bpy", "blender_glb"),
+}
+
+
class AssetPlan(BaseModel):
name: str = Field(description="PascalCase asset name")
- kind: Literal["threejs", "blender_glb"] = Field(
- description="threejs = procedural module; blender_glb = built with bpy and compiled to a GLB"
+ kind: Literal["threejs", "bpy", "blender_glb"] = Field(
+ description="threejs = procedural module; blender_glb = built with bpy and compiled to a GLB",
+ # the schema a planner is handed names the kinds of ITS language (SCENE_ASSET_KINDS): the
+ # default is scene_threejs's, byte-identical to before `bpy` existed; a scene_blender
+ # planner swaps in its own enum
+ json_schema_extra={"enum": list(SCENE_ASSET_KINDS["scene_threejs"])},
)
description: str
approx_size_m: Vec3
diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.py
index d46a5611..86ff95d4 100644
--- a/harness/codeverse3d/conventions.py
+++ b/harness/codeverse3d/conventions.py
@@ -6,7 +6,7 @@ drifted into 3-4 incompatible ``snake_case`` helpers and two up-axes).
Frames
------
-* ``blender`` / ``cadquery`` / ``urdf``: **Z-up, -Y is the object's front**,
+* ``blender`` / ``cadquery`` / ``urdf`` / ``scene_blender``: **Z-up, -Y is the object's front**,
meters. (Blender's "Front" view looks along +Y, so a front face points -Y.)
* ``threejs`` / ``scene_threejs``: **Y-up, +Z is the front**, meters.
* ``glsl_shader`` / ``opengl_python``: **Y-up, +Z front** (GL clip space is
@@ -50,6 +50,8 @@ LANGUAGE_FRAME: dict[str, Frame] = {
"urdf_blender": Frame.Z_UP_NEG_Y_FRONT,
"threejs": Frame.Y_UP_POS_Z_FRONT,
"scene_threejs": Frame.Y_UP_POS_Z_FRONT,
+ # a Blender scene is authored Z-up; its plan, gates and census GLB stay in the GLB frame (D12)
+ "scene_blender": Frame.Z_UP_NEG_Y_FRONT,
# GL clip space is Y-up: graphics output is framed like the three.js/glTF frame.
"glsl_shader": Frame.Y_UP_POS_Z_FRONT,
"opengl_python": Frame.Y_UP_POS_Z_FRONT,
@@ -74,6 +76,16 @@ def to_authoring_frame(v: Sequence[float], language: str, *, extents: bool = Fal
return (x, y, z)
+def glb_basis(language: str) -> tuple[tuple[float, float, float], ...]:
+ """The 3×3 rows taking a ``language``-frame vector into the GLB frame — the glTF export
+ mapping ``(x, y, z) → (x, z, -y)`` for a Z-up language, identity otherwise; the inverse of
+ :func:`to_authoring_frame`. Handed to a harness writer that cannot import this module (the
+ scene_blender census-GLB writer runs inside Blender), so the mapping is still stated once."""
+ if authoring_frame(language) is Frame.Z_UP_NEG_Y_FRONT:
+ return ((1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, -1.0, 0.0))
+ return ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))
+
+
def frame_doc(frame: Frame) -> str:
"""Return the one-paragraph prompt text describing ``frame``."""
if frame is Frame.Z_UP_NEG_Y_FRONT:
diff --git a/harness/codeverse3d/languages/_common.py b/harness/codeverse3d/languages/_common.py
index 87fa7d7e..6cfbec2f 100644
--- a/harness/codeverse3d/languages/_common.py
+++ b/harness/codeverse3d/languages/_common.py
@@ -64,6 +64,22 @@ def line_of(text: str, pos: int) -> int:
return text.count("\n", 0, pos) + 1
+def target_file(target: str | None) -> str:
+ """``src/zones/a.js:12`` → ``src/zones/a.js`` (a finding's target without its line)."""
+ if not target:
+ return ""
+ head, sep, tail = target.rpartition(":")
+ return head if sep and tail.isdigit() else target
+
+
+def target_line(target: str | None) -> int | None:
+ """``src/zones/a.js:12`` → ``12``; ``None`` when the target names no line."""
+ if not target:
+ return None
+ _, sep, tail = target.rpartition(":")
+ return int(tail) if sep and tail.isdigit() else None
+
+
def ws_rel(ws: Workspace, p: Path) -> str:
"""``p`` workspace-relative (posix), or as given when it lies outside the workspace."""
try:
@@ -138,6 +154,7 @@ def compose_build_result(
glb_path: Path | None,
extra_paths: Mapping[str, Path],
output_filter: Callable[[str], str] | None = None,
+ publish: bool = True,
) -> BuildResult:
"""Merge the wrapper's ``build.json`` with the process outcome, and write the result
over it: ``build.json`` is always the BuildResult, the one status file the tools read.
@@ -147,7 +164,8 @@ def compose_build_result(
exists become a failed BuildResult with a typed error (``BUILD_TIMEOUT`` /
``WrapperCrash``) — never an exception — so the orchestrator can route them to repair.
The wrapper's own diagnostics (traceback, warnings, exports …) land in
- ``census["build_report"]``.
+ ``census["build_report"]``. ``publish=False`` leaves ``build_json`` as the wrapper wrote it
+ (a runtime that finishes the build itself — scene_blender probes the census GLB next).
"""
stdout_tail = tail(output_filter(proc.stdout) if output_filter else proc.stdout)
stderr_tail = tail(output_filter(proc.stderr) if output_filter else proc.stderr)
@@ -172,7 +190,8 @@ def compose_build_result(
)
else:
res = _merge_report(read_json_file(build_json), census_json, glb_path, extra_paths, base)
- write_json_atomic(build_json, res.model_dump(mode="json"))
+ if publish:
+ write_json_atomic(build_json, res.model_dump(mode="json"))
return res
diff --git a/harness/codeverse3d/languages/base.py b/harness/codeverse3d/languages/base.py
index 3b272740..902781de 100644
--- a/harness/codeverse3d/languages/base.py
+++ b/harness/codeverse3d/languages/base.py
@@ -117,6 +117,7 @@ _RUNTIMES: dict[Language, tuple[str, str]] = {
Language.THREEJS: ("codeverse3d.languages.threejs", "ThreeJsRuntime"),
Language.URDF_BLENDER: ("codeverse3d.languages.urdf", "UrdfBlenderRuntime"),
Language.SCENE_THREEJS: ("codeverse3d.languages.scene_threejs", "SceneThreeJsRuntime"),
+ Language.SCENE_BLENDER: ("codeverse3d.languages.scene_blender", "SceneBlenderRuntime"),
Language.GLSL_SHADER: ("codeverse3d.languages.glsl_shader", "GlslShaderRuntime"),
Language.OPENGL_PYTHON: ("codeverse3d.languages.opengl_python", "OpenGLPythonRuntime"),
}
diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.py
index 0b3ae162..3aba16c7 100644
--- a/harness/codeverse3d/languages/blender/__init__.py
+++ b/harness/codeverse3d/languages/blender/__init__.py
@@ -74,7 +74,7 @@ REMOVED_BSDF_INPUTS = {
KNOWN_BINDINGS = ("Vector", "Matrix", "Euler", "Quaternion", "bmesh", "math", "random", "np", "numpy", "bpy")
-class _Collector(ast.NodeVisitor):
+class BpyCollector(ast.NodeVisitor):
"""One pass over the tree; rules read the collected facts."""
def __init__(self) -> None:
@@ -164,7 +164,7 @@ class _Collector(ast.NodeVisitor):
def _input_guards(test: ast.expr) -> frozenset[str]:
"""Keys ``k`` a test asserts present: ``'k' in x.inputs`` (also inside an ``and``)."""
if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And):
- return frozenset().union(*(_Collector._input_guards(v) for v in test.values))
+ return frozenset().union(*(BpyCollector._input_guards(v) for v in test.values))
if (isinstance(test, ast.Compare) and len(test.ops) == 1 and isinstance(test.ops[0], ast.In)
and isinstance(test.left, ast.Constant) and isinstance(test.left.value, str)
and isinstance(test.comparators[0], ast.Attribute) and test.comparators[0].attr == "inputs"):
@@ -207,62 +207,60 @@ def _f(kind: LintKind, sev: Severity, msg: str, line: int | None = None, hint: s
return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=data)
-def _rules(c: _Collector, source: str, *, target: str, expect_names: bool, expect_bpy: bool) -> list[GateFinding]:
+
+# The API traps of bpy itself, whatever the file builds: the object lint (``_rules``) and the scene
+# lint (``languages/scene_blender``) both call these, so a Blender rename is learned once.
+def call_traps(c: BpyCollector, name: str, call: ast.Call) -> list[GateFinding]:
+ """Removed / context-dependent operator and method calls (one call)."""
out: list[GateFinding] = []
- E, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741
- if expect_bpy and "bpy" not in c.imports:
- out.append(_f(LintKind.UNDEFINED_NAME, E, f"{target} never imports bpy", 1, "start the file with `import bpy`"))
+ E, W = Severity.ERROR, Severity.WARN
+ if name.startswith("bpy.ops.") and call.args and isinstance(call.args[0], ast.Dict):
+ out.append(_f(LintKind.API_TRAP, E, f"`{name}({{...}})` context-dict override was removed in Blender 4.0", call.lineno,
+ "use `with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj]): bpy.ops....()`"))
+ if name.endswith("primitive_cube_add"):
+ kws = {k.arg for k in call.keywords}
+ if "scale" in kws and "size" not in kws:
+ out.append(_f(LintKind.API_TRAP, W, "primitive_cube_add(scale=...) without size=1 makes a 2 m cube × scale (extents doubled)", call.lineno,
+ "pass `size=1, scale=(sx, sy, sz)` then `bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)`"))
+ if name.endswith("transform_apply"):
+ kws = {k.arg for k in call.keywords}
+ if kws and not {"location", "rotation", "scale"} <= kws:
+ out.append(_f(LintKind.API_TRAP, W, "transform_apply with partial kwargs: unspecified ones default to True (bakes location into mesh data)", call.lineno,
+ "always pass all three: transform_apply(location=False, rotation=False, scale=True)"))
+ if name.endswith("modifier_apply") and not c.has_temp_override:
+ out.append(_f(LintKind.API_TRAP, W, "bpy.ops.object.modifier_apply needs the object active+selected in OBJECT mode", call.lineno,
+ "either leave modifiers unapplied (the exporter applies them) or wrap: `with bpy.context.temp_override(object=obj): bpy.ops.object.modifier_apply(modifier=mod.name)`"))
+ # the rule's own precondition: a script that sets the active object before joining (the urdf
+ # cookbook's `join_as`, one joined object per link) has done what the warning asks
+ if (name.endswith("bpy.ops.object.join") or name == "bpy.ops.object.join") and not any(
+ t.endswith("view_layer.objects.active") for t, _ in c.attr_stores):
+ out.append(_f(LintKind.API_TRAP, W, "bpy.ops.object.join needs all parts selected + an active object; the result inherits the ACTIVE object's transform", call.lineno,
+ "select all, set `bpy.context.view_layer.objects.active = main_obj` (identity transform) before join — or keep parts separate (preferred: named parts)"))
+ if name.endswith("shade_smooth") and any(k.arg == "use_auto_smooth" for k in call.keywords):
+ out.append(_f(LintKind.API_TRAP, E, "shade_smooth(use_auto_smooth=...) was removed in 4.1", call.lineno, "use `bpy.ops.object.shade_smooth_by_angle(angle=0.523599)` or `bpy.ops.object.shade_auto_smooth()`"))
+ if name.endswith(".calc_normals"):
+ out.append(_f(LintKind.API_TRAP, E, "Mesh.calc_normals() was removed in 4.0 (normals are computed automatically)", call.lineno, "delete the call (use me.update() if needed)"))
+ return out
- def _import_finding(kind: str, mod: str, line: int) -> GateFinding:
- if kind == "forbidden":
- return _f(LintKind.FORBIDDEN_IMPORT, E, f"forbidden import `{mod}`", line, "only bpy/bmesh/mathutils/math/random/numpy (+stdlib data helpers) are allowed")
- return _f(LintKind.BAD_IMPORT, W, f"unexpected import `{mod}` (not available / not allowed in the build sandbox)", line, "use only bpy, bmesh, mathutils, math, random, numpy")
- out.extend(check_imports(c.imports, forbidden=FORBIDDEN_IMPORTS, allowed=ALLOWED_IMPORTS, make_finding=_import_finding))
- for name, call in c.calls:
- for prefix, hint in FORBIDDEN_CALL_PREFIXES:
- if name.startswith(prefix):
- out.append(_f(LintKind.SANDBOX, E, f"forbidden call `{name}`", call.lineno, hint))
- for prefix, hint, kind in WARN_CALL_PREFIXES:
- if name.startswith(prefix):
- out.append(_f(kind, W, f"`{name}` — {hint}", call.lineno, hint))
- if name == "open":
- out.append(_f(LintKind.SANDBOX, E, "file IO via open() is forbidden", call.lineno, "no file reads/writes; the harness exports for you"))
- if name.startswith("bpy.ops.") and call.args and isinstance(call.args[0], ast.Dict):
- out.append(_f(LintKind.API_TRAP, E, f"`{name}({{...}})` context-dict override was removed in Blender 4.0", call.lineno,
- "use `with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj]): bpy.ops....()`"))
- if name.endswith("primitive_cube_add"):
- kws = {k.arg for k in call.keywords}
- if "scale" in kws and "size" not in kws:
- out.append(_f(LintKind.API_TRAP, W, "primitive_cube_add(scale=...) without size=1 makes a 2 m cube × scale (extents doubled)", call.lineno,
- "pass `size=1, scale=(sx, sy, sz)` then `bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)`"))
- if name.endswith("transform_apply"):
- kws = {k.arg for k in call.keywords}
- if kws and not {"location", "rotation", "scale"} <= kws:
- out.append(_f(LintKind.API_TRAP, W, "transform_apply with partial kwargs: unspecified ones default to True (bakes location into mesh data)", call.lineno,
- "always pass all three: transform_apply(location=False, rotation=False, scale=True)"))
- if name.endswith("modifier_apply") and not c.has_temp_override:
- out.append(_f(LintKind.API_TRAP, W, "bpy.ops.object.modifier_apply needs the object active+selected in OBJECT mode", call.lineno,
- "either leave modifiers unapplied (the exporter applies them) or wrap: `with bpy.context.temp_override(object=obj): bpy.ops.object.modifier_apply(modifier=mod.name)`"))
- # the rule's own precondition: a script that sets the active object before joining (the urdf
- # cookbook's `join_as`, one joined object per link) has done what the warning asks
- if (name.endswith("bpy.ops.object.join") or name == "bpy.ops.object.join") and not any(
- t.endswith("view_layer.objects.active") for t, _ in c.attr_stores):
- out.append(_f(LintKind.API_TRAP, W, "bpy.ops.object.join needs all parts selected + an active object; the result inherits the ACTIVE object's transform", call.lineno,
- "select all, set `bpy.context.view_layer.objects.active = main_obj` (identity transform) before join — or keep parts separate (preferred: named parts)"))
- if name.endswith("shade_smooth") and any(k.arg == "use_auto_smooth" for k in call.keywords):
- out.append(_f(LintKind.API_TRAP, E, "shade_smooth(use_auto_smooth=...) was removed in 4.1", call.lineno, "use `bpy.ops.object.shade_smooth_by_angle(angle=0.523599)` or `bpy.ops.object.shade_auto_smooth()`"))
- if name.endswith(".calc_normals"):
- out.append(_f(LintKind.API_TRAP, E, "Mesh.calc_normals() was removed in 4.0 (normals are computed automatically)", call.lineno, "delete the call (use me.update() if needed)"))
- for target, line in c.attr_stores:
- if target.endswith(".use_auto_smooth") or target.endswith(".auto_smooth_angle"):
- out.append(_f(LintKind.API_TRAP, E, f"`{target}` was removed in Blender 4.1", line, "use bpy.ops.object.shade_smooth_by_angle(angle=...) or mark sharp edges; or just shade_smooth()"))
- if ".render." in target or target.endswith(".render"):
- out.append(_f(LintKind.HARNESS_OWNED, W, f"render settings touched: `{target}`", line, "the harness owns rendering; delete render/engine/resolution code"))
- if target.endswith("scene.camera") or target.endswith(".world"):
- out.append(_f(LintKind.HARNESS_OWNED, W, f"`{target}` assignment — cameras/world are owned by the harness", line, "remove camera/world code"))
- if target.endswith(".use_nodes"):
- out.append(_f(LintKind.API_TRAP, I, "`use_nodes = True` is a no-op in Blender 5.x (materials always have a node tree); harmless", line, ""))
+def store_traps(target: str, line: int) -> list[GateFinding]:
+ """Assignments to properties Blender 4.1 removed."""
+ if target.endswith(".use_auto_smooth") or target.endswith(".auto_smooth_angle"):
+ return [_f(LintKind.API_TRAP, Severity.ERROR, f"`{target}` was removed in Blender 4.1", line, "use bpy.ops.object.shade_smooth_by_angle(angle=...) or mark sharp edges; or just shade_smooth()")]
+ return []
+
+
+def use_nodes_trap(target: str, line: int) -> list[GateFinding]:
+ if target.endswith(".use_nodes"):
+ return [_f(LintKind.API_TRAP, Severity.INFO, "`use_nodes = True` is a no-op in Blender 5.x (materials always have a node tree); harmless", line, "")]
+ return []
+
+
+def source_traps(c: BpyCollector, source: str) -> list[GateFinding]:
+ """Whole-file traps: removed Principled inputs, bmesh lookup tables, undefined names, the
+ background-mode selection, invalid engine ids."""
+ out: list[GateFinding] = []
+ E, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741
for key, line, guarded in c.bsdf_inputs:
if key in REMOVED_BSDF_INPUTS and not guarded: # `elif 'Specular' in bsdf.inputs:` is version-proof
out.append(_f(LintKind.API_TRAP, E, f"Principled BSDF input '{key}' does not exist in Blender 4.x/5.x (KeyError at runtime)", line,
@@ -289,6 +287,39 @@ def _rules(c: _Collector, source: str, *, target: str, expect_names: bool, expec
for const, line in c.constants:
if const == "BLENDER_EEVEE_NEXT":
out.append(_f(LintKind.HARNESS_OWNED, W, "'BLENDER_EEVEE_NEXT' is not a valid engine id in Blender 5.0", line, "render settings are owned by the harness; delete the line"))
+ return out
+
+
+def _rules(c: BpyCollector, source: str, *, target: str, expect_names: bool, expect_bpy: bool) -> list[GateFinding]:
+ out: list[GateFinding] = []
+ E, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741
+ if expect_bpy and "bpy" not in c.imports:
+ out.append(_f(LintKind.UNDEFINED_NAME, E, f"{target} never imports bpy", 1, "start the file with `import bpy`"))
+
+ def _import_finding(kind: str, mod: str, line: int) -> GateFinding:
+ if kind == "forbidden":
+ return _f(LintKind.FORBIDDEN_IMPORT, E, f"forbidden import `{mod}`", line, "only bpy/bmesh/mathutils/math/random/numpy (+stdlib data helpers) are allowed")
+ return _f(LintKind.BAD_IMPORT, W, f"unexpected import `{mod}` (not available / not allowed in the build sandbox)", line, "use only bpy, bmesh, mathutils, math, random, numpy")
+
+ out.extend(check_imports(c.imports, forbidden=FORBIDDEN_IMPORTS, allowed=ALLOWED_IMPORTS, make_finding=_import_finding))
+ for name, call in c.calls:
+ for prefix, hint in FORBIDDEN_CALL_PREFIXES:
+ if name.startswith(prefix):
+ out.append(_f(LintKind.SANDBOX, E, f"forbidden call `{name}`", call.lineno, hint))
+ for prefix, hint, kind in WARN_CALL_PREFIXES:
+ if name.startswith(prefix):
+ out.append(_f(kind, W, f"`{name}` — {hint}", call.lineno, hint))
+ if name == "open":
+ out.append(_f(LintKind.SANDBOX, E, "file IO via open() is forbidden", call.lineno, "no file reads/writes; the harness exports for you"))
+ out.extend(call_traps(c, name, call))
+ for target, line in c.attr_stores:
+ out.extend(store_traps(target, line))
+ if ".render." in target or target.endswith(".render"):
+ out.append(_f(LintKind.HARNESS_OWNED, W, f"render settings touched: `{target}`", line, "the harness owns rendering; delete render/engine/resolution code"))
+ if target.endswith("scene.camera") or target.endswith(".world"):
+ out.append(_f(LintKind.HARNESS_OWNED, W, f"`{target}` assignment — cameras/world are owned by the harness", line, "remove camera/world code"))
+ out.extend(use_nodes_trap(target, line))
+ out.extend(source_traps(c, source))
pascal = [n for n in c.names_assigned if PASCAL_RE.match(n) and n not in ("Cube", "Cylinder", "Sphere", "Plane")]
if pascal:
out.append(_f(LintKind.CENSUS, I, f"named objects: {sorted(set(pascal))[:12]}", None, ""))
@@ -315,7 +346,7 @@ def lint_blender_source(
msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
findings.append(_f(LintKind.SYNTAX, Severity.ERROR, msg, line, hint, target))
return GateReport.of(GATE, findings, duration_ms=int((time.monotonic() - t0) * 1000))
- c = _Collector()
+ c = BpyCollector()
c.visit(tree)
findings = _rules(c, source, target=target, expect_names=expect_names, expect_bpy=expect_bpy)
for f in findings:
diff --git a/harness/codeverse3d/languages/cadquery/__init__.py b/harness/codeverse3d/languages/cadquery/__init__.py
index fa6ea0b8..495a4ff0 100644
--- a/harness/codeverse3d/languages/cadquery/__init__.py
+++ b/harness/codeverse3d/languages/cadquery/__init__.py
@@ -93,7 +93,7 @@ def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target:
return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data={"line": line} if line else {})
-class _Collector(ImportCollector):
+class BpyCollector(ImportCollector):
def __init__(self) -> None:
super().__init__()
self.calls: list[tuple[str, ast.Call]] = []
@@ -138,7 +138,7 @@ def _top_level_assigned(tree: ast.Module) -> tuple[set[str], set[str]]:
return top, guarded
-def _rules(c: _Collector, tree: ast.Module, source: str) -> list[GateFinding]:
+def _rules(c: BpyCollector, tree: ast.Module, source: str) -> list[GateFinding]:
E, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741
out: list[GateFinding] = []
if "cadquery" not in c.imports:
@@ -197,7 +197,7 @@ def lint_cadquery_source(source: str, *, target: str = "src/model.py") -> GateRe
msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
f = _f(Severity.ERROR, msg, line, hint, target)
return GateReport.of(GATE, [f], duration_ms=int((time.monotonic() - t0) * 1000))
- c = _Collector()
+ c = BpyCollector()
c.visit(tree)
findings = _rules(c, tree, source)
for f in findings:
diff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.py
new file mode 100644
index 00000000..7d82b983
--- /dev/null
+++ b/harness/codeverse3d/languages/scene_blender/__init__.py
@@ -0,0 +1,957 @@
+"""scene_blender: multi-file bpy scenes on the ``scene`` track (DESIGN 2026-09-24 §3, phase 1).
+
+The agent writes ``src/env.py`` / ``src/zones/<snake>.py`` / ``src/assets/<snake>.py`` in the Blender
+frame (``conventions.LANGUAGE_FRAME``: Z up, −Y front, metres); the harness assembles ``src/scene.py``
+(data only: which zones / assets / heroes, and the plan's cameras converted to that frame) and builds
+it in ONE Blender process (``languages/wrappers/run_bpy_scene.py``): every builder isolated, a zone
+that raises dropped with its ``file:line``. The geometry gates are the JS ones, run on the
+harness-written census GLB (``wrappers/_census_glb.py`` → ``runtime_js/lib/glb_scene.mjs``) — one
+implementation of census, placement and camera fitting for both scene languages. The plan stays in
+the GLB frame (D12): only the files the agent reads are converted.
+
+This module: lint (the object track's bpy traps + a scene policy table), layout, skeleton, assembler,
+and the ``SceneRuntime``. Rendering (``render_scene``) is DESIGN phase 2 and not here yet.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import time
+from collections.abc import Sequence
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from pydantic import BaseModel, Field
+
+from codeverse3d.config import Settings, get_settings
+from codeverse3d.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ LintKind,
+ RenderSet,
+ Severity,
+)
+from codeverse3d.contracts.common import ENTRY_FILE, Language
+from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan, ZonePlan
+from codeverse3d.conventions import fmt3, glb_basis, to_authoring_frame, to_pascal, to_snake
+from codeverse3d.languages._ast_lint import (
+ BASE_FORBIDDEN_IMPORTS,
+ check_imports,
+ describe_parse_failure,
+ dotted,
+ safe_parse,
+)
+from codeverse3d.languages._common import (
+ compose_build_result,
+ missing_entry,
+ strip_blender_noise,
+ target_file,
+ target_line,
+ ws_rel,
+)
+from codeverse3d.languages.blender import (
+ BlenderNotFoundError,
+ BpyCollector,
+ blender_env,
+ call_traps,
+ finish_for,
+ source_traps,
+ store_traps,
+ use_nodes_trap,
+)
+from codeverse3d.proc import read_json_or_none, run_subprocess
+from codeverse3d.workspace import Workspace
+
+if TYPE_CHECKING:
+ from codeverse3d.spatial.probes import SceneProbeResult
+
+LANGUAGE = Language.SCENE_BLENDER
+ENTRY_REL = ENTRY_FILE[LANGUAGE] # "src/scene.py"
+GATE = "lint:scene_blender"
+#: the harness's frame clock: ``frame(t) = 1 + round(t * FPS)`` — the wrapper sets it, the render
+#: driver samples it (t = 0 → frame 1, t = 1.5 → frame 46)
+FPS = 30
+TIMES: tuple[float, ...] = (0.0, 1.5)
+
+
+def frame_of(t: float) -> int:
+ """The Blender frame that shows animation time ``t`` (seconds)."""
+ return 1 + round(t * FPS)
+
+
+# ===================================================================== layout
+#: what a whole-scene session edits: the entry and the environment (zones and assets have their own)
+SCENE_FILES: tuple[str, ...] = (ENTRY_REL, "src/env.py")
+#: refine targets that are the environment's, whatever the plan calls its zones
+ENV_WORDS = frozenset({"env", "environment", "lighting", "sky", "fog", "ground", "water", "light", "world", "sun"})
+
+
+def zone_file(name: str) -> str:
+ """``src/zones/<snake>.py`` — the module that builds zone ``name``."""
+ return f"src/zones/{to_snake(name)}.py"
+
+
+def asset_file(asset: AssetPlan) -> str:
+ """A procedural asset's module (``bpy``; a three.js-kind asset in a Blender plan is one too); a
+ hero's compiled GLB."""
+ snake = to_snake(asset.name)
+ return f"public/assets/{snake}.glb" if asset.kind == "blender_glb" else f"src/assets/{snake}.py"
+
+
+def scene_files_for(plan: Plan | None, target: str, *, alias: dict[str, str] | None = None) -> list[str]:
+ """The files that own a scene refine target — the same routing as scene_threejs's
+ (``languages.scene_threejs.scene_files_for``), over this language's file table."""
+ zone_plans = list(getattr(plan, "zones", None) or [])
+ zones = {to_snake(z.name) for z in zone_plans}
+ assets = {to_snake(a.name): a for a in (getattr(plan, "assets", None) or [])}
+ survivor = {to_snake(k): v for k, v in (alias or {}).items()}
+ key = to_snake(target)
+ if key in zones:
+ return [zone_file(key)]
+ if key in assets:
+ if assets[key].kind != "blender_glb":
+ return [asset_file(assets[key].model_copy(update={"name": survivor.get(key, key)}))]
+ return [zone_file(z.name) for z in zone_plans if key in {to_snake(c) for c in z.contents}]
+ if key in {to_snake(c.name) for c in (getattr(plan, "cameras", None) or [])} or key in ("camera", "cameras", "composition"):
+ return [ENTRY_REL]
+ if key in ENV_WORDS:
+ return ["src/env.py"]
+ if "/" in target and to_snake(target.split("/", 1)[0]) in zones:
+ return [zone_file(target.split("/", 1)[0])]
+ return []
+
+
+def module_files(ws: Workspace, sub: str) -> list[Path]:
+ """``src/<sub>/*.py`` (sorted; ``_`` helper modules excluded)."""
+ d = ws.src / sub
+ return sorted(p for p in d.glob("*.py") if not p.name.startswith("_")) if d.is_dir() else []
+
+
+def hero_files(ws: Workspace) -> list[Path]:
+ d = ws.public / "assets"
+ return sorted(d.glob("*.glb")) if d.is_dir() else []
+
+
+# ===================================================================== lint
+ALLOWED_IMPORTS = frozenset({
+ "bpy", "bmesh", "mathutils", "math", "random", "numpy", "itertools", "functools", "collections", "typing",
+ "dataclasses", "colorsys", "statistics", "operator", "enum", "copy", "__future__", "bpy_extras",
+ "env", "zones", "assets", "lib", # the workspace's own packages (src/ is on sys.path)
+})
+#: the object track's floor + everything that reads a clock or the file system: a scene is
+#: deterministic by construction and the harness owns every file
+FORBIDDEN_IMPORTS = frozenset(BASE_FORBIDDEN_IMPORTS | {"os", "sys", "pathlib", "time", "datetime", "tempfile",
+ "glob", "io", "shlex"})
+#: numpy's random module is fine only through a seeded generator
+_SEEDED_NP = ("np.random.default_rng", "numpy.random.default_rng", "np.random.RandomState", "numpy.random.RandomState")
+#: the scene policy table: dotted-call prefix → (severity, kind, message, hint)
+CALL_POLICY: tuple[tuple[str, Severity, LintKind, str, str], ...] = (
+ ("bpy.ops.render.", Severity.ERROR, LintKind.HARNESS_OWNED, "rendering is the harness's", "delete every bpy.ops.render.* call"),
+ ("bpy.ops.wm.", Severity.ERROR, LintKind.HARNESS_OWNED, "file open/save/append/link is the harness's",
+ "delete it; the harness saves the .blend"),
+ ("bpy.ops.export_", Severity.ERROR, LintKind.HARNESS_OWNED, "export is the harness's", "delete it"),
+ ("bpy.ops.import_", Severity.ERROR, LintKind.HARNESS_OWNED, "imports are the harness's",
+ "a hero GLB is already imported: place ctx.assets['<snake>'] as a collection instance"),
+ ("bpy.ops.image.save", Severity.ERROR, LintKind.SANDBOX, "no image file writes", "delete it"),
+ ("bpy.data.libraries.", Severity.ERROR, LintKind.SANDBOX, "no linking/appending external .blend data",
+ "build it procedurally"),
+ ("bpy.data.cameras.new", Severity.ERROR, LintKind.HARNESS_OWNED, "cameras are the harness's (the plan's cameras)",
+ "delete camera creation"),
+ ("bpy.ops.object.camera_add", Severity.ERROR, LintKind.HARNESS_OWNED, "cameras are the harness's (the plan's cameras)",
+ "delete camera creation"),
+ ("bpy.app.timers.", Severity.ERROR, LintKind.HARNESS_OWNED, "timers never run in a headless build", "delete it"),
+ ("subprocess.", Severity.ERROR, LintKind.SANDBOX, "no subprocesses", "delete it"),
+ ("os.", Severity.ERROR, LintKind.SANDBOX, "no file-system or process access", "delete it"),
+ ("shutil.", Severity.ERROR, LintKind.SANDBOX, "no file IO", "delete it"),
+ ("sys.exit", Severity.ERROR, LintKind.SANDBOX, "do not exit; the harness runs every builder", "delete it"),
+ ("bpy.ops.view3d.", Severity.WARN, LintKind.API_TRAP, "view3d operators fail in background mode (no 3D viewport)", "delete it"),
+ ("bpy.ops.screen.", Severity.WARN, LintKind.API_TRAP, "screen operators fail in background mode", "delete it"),
+)
+#: scene settings the harness owns: an assigned dotted target that CONTAINS one of these (a
+#: material's ``cycles`` or a modifier's ``render_levels`` are the agent's, so the dots matter)
+_STORE_OWNED_IN: tuple[tuple[str, str], ...] = (
+ ("scene.render.", "render settings"), ("scene.cycles.", "Cycles settings"), ("scene.eevee.", "EEVEE settings"),
+ ("scene.view_settings.", "colour management"), ("scene.display_settings.", "colour management"),
+)
+#: ... or ENDS with one of these
+_STORE_OWNED_END: tuple[tuple[str, str], ...] = (
+ ("scene.camera", "the active camera"), ("scene.frame_start", "the frame range"), ("scene.frame_end", "the frame range"),
+ ("scene.frame_current", "the current frame"), ("scene.render", "render settings"),
+)
+#: Blender's simple-expression driver subset (verified on 5.0.1: ``driver.is_simple_expression``);
+#: anything else runs Python, which a ``--factory-startup`` build silently evaluates to 0 (D10)
+SIMPLE_DRIVER_FUNCS = frozenset({
+ "radians", "degrees", "abs", "fabs", "floor", "ceil", "trunc", "round", "int", "sin", "cos", "tan", "asin",
+ "acos", "atan", "atan2", "exp", "log", "sqrt", "smoothstep", "fmod", "pow", "min", "max", "clamp", "lerp",
+})
+_SIMPLE_NODES = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Compare, ast.BoolOp, ast.IfExp, ast.Call, ast.Name,
+ ast.Constant, ast.Load, ast.Add, ast.Sub, ast.Mult, ast.Div, ast.USub, ast.UAdd, ast.Not, ast.And,
+ ast.Or, ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE)
+
+
+def simple_driver(expr: str) -> bool:
+ """Is ``expr`` inside Blender's simple-expression subset (no Python needed to evaluate it)?"""
+ try:
+ tree = ast.parse(expr.strip(), mode="eval")
+ except (SyntaxError, ValueError, RecursionError, MemoryError):
+ return False
+ for node in ast.walk(tree):
+ if not isinstance(node, _SIMPLE_NODES):
+ return False
+ if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float, bool)):
+ return False
+ if isinstance(node, ast.Call) and not (isinstance(node.func, ast.Name) and node.func.id in SIMPLE_DRIVER_FUNCS
+ and not node.keywords):
+ return False
+ return True
+
+
+class _SceneFacts(ast.NodeVisitor):
+ """What the scene policy needs beyond the object-track collector: primitive operators inside
+ loops, handler access, driver expressions, unseeded randomness, links into the scene root."""
+
+ def __init__(self) -> None:
+ self.loop_ops: list[tuple[str, int]] = []
+ self.handlers: list[int] = []
+ self.expressions: list[tuple[str, int]] = []
+ self.use_self: list[int] = []
+ self.random_calls: list[tuple[str, int]] = []
+ self.random_names: list[tuple[str, int]] = []
+ self.root_links: list[int] = []
+ self._loops = 0
+
+ def _loop(self, node: ast.For | ast.While | ast.comprehension) -> None:
+ self._loops += 1
+ self.generic_visit(node)
+ self._loops -= 1
+
+ visit_For = visit_While = visit_ListComp = visit_GeneratorExp = _loop # type: ignore[assignment]
+
+ def visit_Attribute(self, node: ast.Attribute) -> None:
+ if dotted(node) == "bpy.app.handlers" or dotted(node).startswith("bpy.app.handlers."):
+ self.handlers.append(node.lineno)
+ self.generic_visit(node)
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ if (node.module or "") == "random":
+ self.random_names += [(a.name, node.lineno) for a in node.names if a.name != "Random"]
+ if (node.module or "").startswith("bpy.app") and any(a.name == "handlers" for a in node.names):
+ self.handlers.append(node.lineno)
+
+ def visit_Call(self, node: ast.Call) -> None:
+ name = dotted(node.func)
+ if self._loops and name.startswith("bpy.ops.mesh.primitive_"):
+ self.loop_ops.append((name, node.lineno))
+ if name.startswith("random.") and not (name == "random.Random" and node.args):
+ self.random_calls.append((name, node.lineno))
+ if name.startswith(("np.random.", "numpy.random.")) and not (name in _SEEDED_NP and node.args):
+ self.random_calls.append((name, node.lineno))
+ if name.endswith("scene.collection.objects.link") or name.endswith("scene.collection.children.link"):
+ self.root_links.append(node.lineno)
+ self.generic_visit(node)
+
+ def visit_Assign(self, node: ast.Assign) -> None:
+ for t in node.targets:
+ d = dotted(t)
+ if d.endswith(".expression") and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
+ self.expressions.append((node.value.value, node.lineno))
+ if d.endswith(".use_self"):
+ self.use_self.append(node.lineno)
+ self.generic_visit(node)
+
+
+def _f(kind: LintKind, sev: Severity, msg: str, line: int | None, hint: str, target: str) -> GateFinding:
+ data: dict[str, object] = {"kind": kind.value}
+ if line:
+ data["line"] = line
+ return GateFinding(gate=GATE, severity=sev, target=f"{target}:{line}" if line else target, message=msg,
+ fix_hint=hint, data=data)
+
+
+def _regate(findings: list[GateFinding], target: str) -> list[GateFinding]:
+ """The object track's bpy traps, re-stamped as this gate's findings on ``target``."""
+ out = []
+ for f in findings:
+ line = f.data.get("line")
+ out.append(f.model_copy(update={"gate": GATE, "target": f"{target}:{line}" if line else target}))
+ return out
+
+
+def _policy(c: BpyCollector, facts: _SceneFacts, *, target: str, role: str) -> list[GateFinding]:
+ out: list[GateFinding] = []
+ E, W = Severity.ERROR, Severity.WARN
+
+ def _import_finding(kind: str, mod: str, line: int) -> GateFinding:
+ if kind == "forbidden":
+ return _f(LintKind.FORBIDDEN_IMPORT, E, f"forbidden import `{mod}`", line,
+ "a scene uses bpy / bmesh / mathutils / math / numpy and ctx.rng(seed); no clock, no files", target)
+ return _f(LintKind.BAD_IMPORT, W, f"unexpected import `{mod}` (not available in the build)", line,
+ "use bpy, bmesh, mathutils, math, numpy and your own src/ modules", target)
+
+ out.extend(check_imports(c.imports, forbidden=FORBIDDEN_IMPORTS, allowed=ALLOWED_IMPORTS, make_finding=_import_finding))
+ for name, call in c.calls:
+ for prefix, sev, kind, msg, hint in CALL_POLICY:
+ if name.startswith(prefix):
+ out.append(_f(kind, sev, f"`{name}`: {msg}", call.lineno, hint, target))
+ if name == "open":
+ out.append(_f(LintKind.SANDBOX, E, "file IO via open() is forbidden", call.lineno, "the harness writes every file", target))
+ if name.endswith(".frame_set"):
+ out.append(_f(LintKind.HARNESS_OWNED, E, f"`{name}`: the harness samples the frames", call.lineno,
+ "animate with keyframes / simple drivers; never set the frame", target))
+ if role != "env" and name.startswith("bpy.data.worlds.new"):
+ out.append(_f(LintKind.HARNESS_OWNED, E, "the world is src/env.py's", call.lineno, "build the world in build_env(ctx)", target))
+ out.extend(_regate(call_traps(c, name, call), target))
+ for store, line in c.attr_stores:
+ out.extend(_regate(store_traps(store, line), target))
+ owned = next((what for key, what in _STORE_OWNED_IN if key in store), None) or next(
+ (what for key, what in _STORE_OWNED_END if store.endswith(key)), None)
+ if owned:
+ out.append(_f(LintKind.HARNESS_OWNED, E, f"`{store}`: {owned} are the harness's", line, "delete the assignment", target))
+ if role != "env" and store.endswith(".world"):
+ out.append(_f(LintKind.HARNESS_OWNED, E, f"`{store}`: the world is src/env.py's", line, "build the world in build_env(ctx)", target))
+ out.extend(_regate(use_nodes_trap(store, line), target))
+ for const, line in c.constants:
+ if const == "NISHITA":
+ out.append(_f(LintKind.API_TRAP, E, "sky_type 'NISHITA' was renamed in Blender 5.0 (it raises)", line,
+ "sky.sky_type = 'MULTIPLE_SCATTERING'", target))
+ for line in facts.handlers[:1]:
+ out.append(_f(LintKind.HARNESS_OWNED, E, "bpy.app.handlers: a frame hook does not travel with the .blend", line,
+ "animate with keyframes, simple drivers on `frame` or the geometry-nodes Scene Time node", target))
+ for expr, line in facts.expressions:
+ if not simple_driver(expr):
+ out.append(_f(LintKind.API_TRAP, E, f"driver expression {expr!r} needs Python, which the build never runs (it evaluates to 0)",
+ line, "keyframes, or a simple expression of `frame` (sin/cos/min/max/clamp/lerp, + - * /, "
+ "comparisons; no attribute access, no ** or %)", target))
+ for line in facts.use_self[:1]:
+ out.append(_f(LintKind.API_TRAP, E, "driver.use_self needs Python, which the build never runs", line,
+ "use a driver variable or keyframes", target))
+ for name, line in facts.random_calls[:1] + facts.random_names[:1]:
+ out.append(_f(LintKind.NONDETERMINISM, E, f"`{name}`: unseeded randomness", line,
+ "rng = ctx.rng(seed); rng.uniform(a, b) — the only randomness a scene uses", target))
+ for name, line in facts.loop_ops[:1]:
+ out.append(_f(LintKind.HANG_RISK, W, f"`{name}` inside a loop: every operator call rebuilds the scene state", line,
+ "build meshes with bmesh / bpy.data, or model once and place collection instances", target))
+ if role == "zone":
+ for line in facts.root_links[:1]:
+ out.append(_f(LintKind.LAYOUT, W, "linked into the scene root: it will not belong to this zone", line,
+ "ctx.collection.objects.link(obj)", target))
+ return out
+
+
+def lint_scene_source(source: str, *, target: str, role: str) -> list[GateFinding]:
+ """Lint one scene module; ``role`` is ``entry`` / ``env`` / ``zone`` / ``asset`` / ``helper``."""
+ tree, exc = safe_parse(source, target)
+ if tree is None:
+ msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
+ return [_f(LintKind.SYNTAX, Severity.ERROR, msg, line, hint, target)]
+ c = BpyCollector()
+ c.visit(tree)
+ facts = _SceneFacts()
+ facts.visit(tree)
+ out = _policy(c, facts, target=target, role=role)
+ out.extend(_regate(source_traps(c, source), target))
+ out.extend(_exports(tree, target=target, role=role))
+ return out
+
+
+def _exports(tree: ast.Module, *, target: str, role: str) -> list[GateFinding]:
+ defs = {n.name for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ stem = Path(target).stem
+ need = {"zone": ("build", "build(ctx) -> bpy.types.Collection: link everything into ctx.collection and return it"),
+ "asset": (f"build_{stem}", f"build_{stem}(ctx, variant=0) -> bpy.types.Collection, built at the origin, base on z = 0"),
+ "env": ("build_env", "build_env(ctx) -> dict: world, sun, ground, atmosphere")}.get(role)
+ out = []
+ if need and need[0] not in defs:
+ out.append(_f(LintKind.LAYOUT, Severity.ERROR, f"{target} defines no `{need[0]}`", None, f"define {need[1]}", target))
+ if role == "env" and "height_at" not in defs:
+ out.append(_f(LintKind.LAYOUT, Severity.WARN, "src/env.py defines no height_at(x, y)", None,
+ "define height_at(x, y) -> z (the ground the zones seat on; the harness uses z = 0 without it)", target))
+ return out
+
+
+def _role(ws: Workspace, p: Path) -> str:
+ if p == ws.root / ENTRY_REL:
+ return "entry"
+ if p == ws.src / "env.py":
+ return "env"
+ if p.parent == ws.src / "zones" and not p.name.startswith("_"):
+ return "zone"
+ if p.parent == ws.src / "assets" and not p.name.startswith("_"):
+ return "asset"
+ return "helper"
+
+
+def lint(ws: Workspace) -> GateReport:
+ """Every ``src/**.py`` except the harness's own library (``src/lib/``, syntax only); passed iff no ERROR."""
+ t0 = time.monotonic()
+ findings: list[GateFinding] = []
+ if not (ws.root / ENTRY_REL).is_file():
+ findings.append(_f(LintKind.MISSING_FILE, Severity.ERROR, f"{ENTRY_REL} is missing", None,
+ "the harness assembles src/scene.py; re-run the assemble step", ENTRY_REL))
+ for p in sorted(ws.src.rglob("*.py")) if ws.src.is_dir() else []:
+ rel = ws_rel(ws, p)
+ source = p.read_text(errors="replace")
+ if p.is_relative_to(ws.src / "lib"):
+ tree, exc = safe_parse(source, rel)
+ if tree is None:
+ msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
+ findings.append(_f(LintKind.SYNTAX, Severity.ERROR, msg, line, hint, rel))
+ continue
+ role = _role(ws, p)
+ if role in ("zone", "asset") and p.stem != to_snake(p.stem):
+ findings.append(_f(LintKind.NAMING, Severity.ERROR, f"module name '{p.name}' is not snake_case", None,
+ f"rename it to {to_snake(p.stem)}.py", rel))
+ findings.extend(lint_scene_source(source, target=rel, role=role))
+ return GateReport.of(GATE, findings, duration_ms=int((time.monotonic() - t0) * 1000))
+
+
+# ===================================================================== skeleton
+def _v(v: Sequence[float], *, extents: bool = False) -> tuple[float, float, float]:
+ """A plan (GLB-frame) vector in this language's frame (D12: prompts and skeleton convert)."""
+ return tuple(round(c, 3) for c in to_authoring_frame(v, LANGUAGE.value, extents=extents)) # type: ignore[return-value]
+
+
+def _env_source(plan: ScenePlan) -> str:
+ c, e = _v(plan.bounds.center), _v(plan.bounds.extents, extents=True)
+ span = max(e[0], e[1], 40.0)
+ ground = round(max(120.0, span * 2.5), 1)
+ fog_h = round(max(e[2] * 2.0, 20.0), 1)
+ interior = "True" if plan.interior else "False"
+ return f'''"""src/env.py — the environment: world (sky), sun, ground, atmosphere{", enclosure" if plan.interior else ""}.
+
+ENV PLAN: {plan.environment.strip()}
+setting: {plan.setting.strip()} mood: {plan.mood.strip()}
+Frame: Z up, -Y front, metres. BOUNDS below are the plan's, in this frame.
+CONTRACT: height_at(x, y) -> z is THE ground: the terrain mesh and every zone's seat use it.
+ build_env(ctx) -> dict builds the world, lamps, ground and atmosphere into ctx.collection and returns
+ what zones may share (materials, water level, sun direction ...) — they read it as ctx.env.
+ Rewrite the sky / sun / ground / fog below to match the plan; keep build_env and height_at.
+"""
+import math
+
+import bmesh
+import bpy
+from mathutils import Vector
+
+BOUNDS = {{"center": ({fmt3(c)}), "extents": ({fmt3(e)})}}
+INTERIOR = {interior}
+GROUND_SIZE = {ground}
+SUN_AZIMUTH_DEG = 45.0 # compass angle of the sun: 0 = +X, 90 = +Y
+SUN_ELEVATION_DEG = 35.0
+
+
+def height_at(x, y):
+ """z of the ground at (x, y) — flat until you shape it (then the ground mesh follows)."""
+ return 0.0
+
+
+def _material(name, rgb, roughness=0.8, metallic=0.0):
+ mat = bpy.data.materials.new(name)
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (rgb[0], rgb[1], rgb[2], 1.0)
+ bsdf.inputs["Roughness"].default_value = roughness
+ bsdf.inputs["Metallic"].default_value = metallic
+ return mat
+
+
+def _ground(ctx, material):
+ me = bpy.data.meshes.new("Ground")
+ bm = bmesh.new()
+ bmesh.ops.create_grid(bm, x_segments=96, y_segments=96, size=GROUND_SIZE / 2)
+ for v in bm.verts:
+ v.co.z = height_at(v.co.x, v.co.y)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(material)
+ ob = bpy.data.objects.new("Ground", me)
+ ctx.collection.objects.link(ob)
+ return ob
+
+
+def _sky(ctx):
+ world = bpy.data.worlds.new("Sky")
+ ctx.scene.world = world
+ nodes, links = world.node_tree.nodes, world.node_tree.links
+ sky = nodes.new("ShaderNodeTexSky")
+ sky.sky_type = "MULTIPLE_SCATTERING"
+ sky.sun_elevation = math.radians(SUN_ELEVATION_DEG)
+ sky.sun_rotation = math.radians(SUN_AZIMUTH_DEG)
+ links.new(sky.outputs["Color"], nodes["Background"].inputs["Color"])
+ nodes["Background"].inputs["Strength"].default_value = 0.4
+
+
+def _sun(ctx):
+ az, el = math.radians(SUN_AZIMUTH_DEG), math.radians(SUN_ELEVATION_DEG)
+ towards_sun = Vector((math.cos(el) * math.cos(az), math.cos(el) * math.sin(az), math.sin(el)))
+ lamp = bpy.data.lights.new("Sun", "SUN")
+ lamp.energy = 3.0
+ ob = bpy.data.objects.new("Sun", lamp)
+ ob.rotation_euler = (-towards_sun).to_track_quat("-Z", "Y").to_euler()
+ ctx.collection.objects.link(ob)
+ return towards_sun
+
+
+def _atmosphere(ctx):
+ """A bounded fog volume over the scene (a world volume over a large scene swallows the sun)."""
+ cx, cy, _ = BOUNDS["center"]
+ me = bpy.data.meshes.new("Atmosphere")
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=(GROUND_SIZE, GROUND_SIZE, {fog_h}), verts=bm.verts)
+ bmesh.ops.translate(bm, vec=(cx, cy, {fog_h / 2}), verts=bm.verts)
+ bm.to_mesh(me)
+ bm.free()
+ mat = bpy.data.materials.new("AtmosphereFog")
+ nodes, links = mat.node_tree.nodes, mat.node_tree.links
+ nodes.remove(nodes["Principled BSDF"])
+ fog = nodes.new("ShaderNodeVolumePrincipled")
+ fog.inputs["Density"].default_value = {0.001 if plan.interior else 0.002}
+ links.new(fog.outputs["Volume"], nodes["Material Output"].inputs["Volume"])
+ me.materials.append(mat)
+ ctx.collection.objects.link(bpy.data.objects.new("Atmosphere", me))
+
+
+def _enclosure(ctx, material):
+ """Floor, walls and ceiling on the bounds' faces (an interior's shell; cut the openings)."""
+ (cx, cy, cz), (ex, ey, ez) = BOUNDS["center"], BOUNDS["extents"]
+ t = 0.2
+ slabs = {{
+ "Floor": ((cx, cy, cz - ez / 2 - t / 2), (ex, ey, t)),
+ "Ceiling": ((cx, cy, cz + ez / 2 + t / 2), (ex, ey, t)),
+ "WallBack": ((cx, cy + ey / 2 + t / 2, cz), (ex, t, ez)),
+ "WallLeft": ((cx - ex / 2 - t / 2, cy, cz), (t, ey, ez)),
+ "WallRight": ((cx + ex / 2 + t / 2, cy, cz), (t, ey, ez)),
+ }}
+ for name, (centre, size) in slabs.items():
+ me = bpy.data.meshes.new(name)
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=size, verts=bm.verts)
+ bmesh.ops.translate(bm, vec=centre, verts=bm.verts)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(material)
+ ctx.collection.objects.link(bpy.data.objects.new(name, me))
+ lamp = bpy.data.lights.new("CeilingLight", "AREA")
+ lamp.energy = 40.0 * ex * ey
+ lamp.size = max(0.5, min(ex, ey) * 0.5)
+ ob = bpy.data.objects.new("CeilingLight", lamp)
+ ob.location = (cx, cy, cz + ez / 2 - 0.05)
+ ctx.collection.objects.link(ob)
+
+
+def build_env(ctx):
+ _sky(ctx)
+ sun = _sun(ctx)
+ ground_mat = _material("GroundMat", (0.28, 0.33, 0.22))
+ _ground(ctx, ground_mat)
+ if INTERIOR:
+ _enclosure(ctx, _material("WallMat", (0.72, 0.68, 0.6)))
+ _atmosphere(ctx)
+ return {{"ground_material": ground_mat, "sun_direction": tuple(sun)}}
+'''
+
+
+def _asset_source(a: AssetPlan) -> str:
+ snake, pascal = to_snake(a.name), to_pascal(a.name)
+ w, h, d = (max(0.05, float(v)) for v in a.approx_size_m) # plan order: width, height, depth
+ rgb, rough, metal = finish_for(a.description)
+ return f'''"""src/assets/{snake}.py — asset "{pascal}": {a.description.strip()}
+
+approx size {w:g} x {d:g} x {h:g} m (x = width, y = depth, z = height); expected instances: ~{a.instances_hint}
+CONTRACT: build_{snake}(ctx, variant=0) -> bpy.types.Collection — link every part into ctx.collection
+ (named '{pascal}'), built ONCE at the origin with its base on z = 0, front facing -Y. Zones place
+ collection instances of it (ctx.assets['{snake}']); never link it anywhere else.
+"""
+import bmesh
+import bpy
+
+
+def build_{snake}(ctx, variant=0):
+ mat = bpy.data.materials.new("{pascal}Mat")
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = ({fmt3(rgb)}, 1.0)
+ bsdf.inputs["Roughness"].default_value = {rough}
+ bsdf.inputs["Metallic"].default_value = {metal}
+ # PLACEHOLDER blockout at the planned size — REPLACE with the real construction (several parts).
+ me = bpy.data.meshes.new("{pascal}Body")
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=({w:g}, {d:g}, {h:g}), verts=bm.verts)
+ bmesh.ops.translate(bm, vec=(0.0, 0.0, {h / 2:g}), verts=bm.verts)
+ bm.to_mesh(me)
+ bm.free()
+ me.materials.append(mat)
+ ctx.collection.objects.link(bpy.data.objects.new("{pascal}Body", me))
+ return ctx.collection
+'''
+
+
+def _zone_source(z: ZonePlan, assets: dict[str, AssetPlan], counters: dict[str, int]) -> str:
+ """A zone stub placing each planned asset once; ``counters`` numbers the placed copies across
+ zones, because a Blender object name is global (a second ``Lantern_0`` would be ``Lantern_0.001``)."""
+ snake, pascal = to_snake(z.name), to_pascal(z.name)
+ c, e = _v(z.bbox.center), _v(z.bbox.extents, extents=True)
+ places = []
+ for i, name in enumerate(z.contents):
+ a = assets.get(to_snake(name))
+ if a is None:
+ continue
+ ox = (-e[0] / 4 + (i % 3) * e[0] / 4) if len(z.contents) > 1 else 0.0
+ oy = (-e[1] / 4 + (i // 3) * e[1] / 4) if len(z.contents) > 3 else 0.0
+ n = counters.get(to_snake(a.name), 0)
+ counters[to_snake(a.name)] = n + 1
+ places.append(f' place(ctx, "{to_snake(a.name)}", "{to_pascal(a.name)}_{n}", {round(c[0] + ox, 2)}, {round(c[1] + oy, 2)})')
+ body = "\n".join(places) or " pass # TODO: build this zone's content (seat everything with ctx.height_at(x, y))"
+ return f'''"""src/zones/{snake}.py — zone "{pascal}": {z.description.strip()}
+
+PLAN bbox (Z up, -Y front, metres): centre ({fmt3(c)}) extents ({fmt3(e)}). Contents: {", ".join(z.contents) or "-"}
+CONTRACT: build(ctx) -> bpy.types.Collection — ctx.collection is this zone's (named '{pascal}', active,
+ so bpy.ops primitives land in it); every PLACED thing is ONE root object in it, named <Name>_<i>
+ (object names are global in Blender: never reuse one another zone uses). Seat things on
+ ctx.height_at(x, y); keep them inside the bbox. Assets: a collection-instance Empty of
+ ctx.assets['<snake>']. Animation is data: keyframes, or simple drivers on `frame`.
+"""
+import bpy
+
+
+def place(ctx, key, name, x, y, rot_z=0.0):
+ """One placed copy of asset `key`: a collection-instance Empty seated on the ground."""
+ source = ctx.assets.get(key)
+ if source is None:
+ return None
+ ob = bpy.data.objects.new(name, None)
+ ob.instance_type = "COLLECTION"
+ ob.instance_collection = source
+ ob.location = (x, y, ctx.height_at(x, y))
+ ob.rotation_euler[2] = rot_z
+ ctx.collection.objects.link(ob)
+ return ob
+
+
+def build(ctx):
+{body}
+ return ctx.collection
+'''
+
+
+def _cam(c: CameraPlan) -> str:
+ return (f' {{"name": "{to_snake(c.name)}", "location": ({fmt3(_v(c.position))}), '
+ f'"look_at": ({fmt3(_v(c.look_at))}), "fov": {c.fov:g}}},')
+
+
+def render_scene_py(zones: Sequence[str], assets: Sequence[str], heroes: Sequence[str], cameras: Sequence[CameraPlan],
+ *, title: str = "", summary: str = "") -> str:
+ """Deterministic ``src/scene.py``: data the wrapper reads, nothing to execute."""
+ def table(keys: Sequence[str]) -> str:
+ return "{\n" + "".join(f' "{k}": "{to_pascal(k)}",\n' for k in keys) + "}" if keys else "{}"
+
+ plan_line = f"PLAN: {title} — {summary.strip()}\n" if title else ""
+ return f'''"""src/scene.py — ASSEMBLED BY THE HARNESS (codeverse3d assembler). Edit env / zones / assets
+instead; re-assembly overwrites this file.
+{plan_line}
+The harness builds the scene in one Blender process: env.build_env(ctx); every hero GLB and asset
+module (build_<snake>(ctx)); then every zone's build(ctx) — each on its own (a zone that raises is
+dropped and reported with its file:line); then the CAMERAS below (Z up, -Y front, metres; fov is
+the VERTICAL field of view in degrees). The census is the t = 0 pose, frame 1.
+"""
+
+ZONES = {table(zones)}
+ASSETS = {table(assets)}
+HEROES = {table(heroes)}
+CAMERAS = [
+{chr(10).join(_cam(c) for c in cameras)}
+]
+'''
+
+
+def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
+ """Starter files for a scene plan (env, one module per zone and per procedural asset, the
+ assembled entry); ``public/assets/`` for the heroes."""
+ if not isinstance(plan, ScenePlan):
+ raise TypeError(f"scene_blender needs a ScenePlan, got {type(plan).__name__}")
+ written: list[Path] = []
+
+ def put(rel: str, text: str) -> None:
+ path = ws.root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ written.append(path)
+
+ put("src/env.py", _env_source(plan))
+ assets = {to_snake(a.name): a for a in plan.assets}
+ for a in plan.assets:
+ if a.kind != "blender_glb":
+ put(asset_file(a), _asset_source(a))
+ counters: dict[str, int] = {}
+ for z in plan.zones:
+ put(zone_file(z.name), _zone_source(z, assets, counters))
+ put(ENTRY_REL, render_scene_py([to_snake(z.name) for z in plan.zones],
+ [to_snake(a.name) for a in plan.assets if a.kind != "blender_glb"], [],
+ list(plan.cameras[:6]), title=plan.title, summary=plan.summary))
+ (ws.public / "assets").mkdir(parents=True, exist_ok=True)
+ return written
+
+
+# ===================================================================== build
+WRAPPER = Path(__file__).resolve().parent.parent / "wrappers" / "run_bpy_scene.py"
+#: what a build (re)writes under ``artifacts/`` — wiped first, so nothing of a previous build reads as current
+BUILD_OUTPUTS = ("build.json", "census.json", "census.glb", "scene.blend", "bpy_build.json", "bpy_census.json",
+ "scene_probe.json")
+
+
+class WrapperRun(BaseModel):
+ """One Blender process over the workspace: the wrapper's report as a BuildResult (typed
+ timeout / crash / script error), its raw report and the bpy facts."""
+
+ result: BuildResult
+ report: dict[str, Any] = Field(default_factory=dict)
+ facts: dict[str, Any] = Field(default_factory=dict)
+
+
+def _fallback_camera(plan: ScenePlan | None) -> CameraPlan:
+ if plan is None:
+ return CameraPlan(name="overview", position=(30.0, 18.0, 30.0), look_at=(0.0, 1.0, 0.0), fov=50.0)
+ c, e = plan.bounds.center, plan.bounds.extents
+ r = max(e[0], e[2], 10.0)
+ return CameraPlan(name="overview", position=(c[0] + 0.8 * r, c[1] + 0.5 * r, c[2] + 0.8 * r), look_at=c, fov=50.0,
+ purpose="fallback: the plan names no camera")
+
+
+class AssembleResult(BaseModel):
+ scene_path: str
+ zones_included: list[str] = Field(default_factory=list)
+ zones_failed: dict[str, str] = Field(default_factory=dict)
+ env_ok: bool = True
+ cameras: list[CameraPlan] = Field(default_factory=list)
+ warnings: list[str] = Field(default_factory=list)
+ census: dict[str, Any] = Field(default_factory=dict)
+
+
+class SceneBlenderRuntime:
+ """``SceneRuntime`` for ``Language.SCENE_BLENDER``."""
+
+ language = LANGUAGE
+ entry_globs: tuple[str, ...] = (ENTRY_REL, "src/zones/*.py", "src/assets/*.py", "src/env.py")
+
+ zone_file = staticmethod(zone_file)
+ asset_file = staticmethod(asset_file)
+
+ def __init__(self, *, blender: str | None = None, settings: Settings | None = None) -> None:
+ self._settings = settings or get_settings()
+ self._blender = blender
+
+ # ------------------------------------------------------------------ layout
+ def expected_files(self, plan: Plan | None) -> list[str]:
+ return list(SCENE_FILES)
+
+ def files_for(self, plan: Plan | None, target: str, *, alias: dict[str, str] | None = None) -> list[str]:
+ return scene_files_for(plan, target, alias=alias)
+
+ def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint(ws)
+
+ # ------------------------------------------------------------------ the Blender process
+ def blender_binary(self) -> str:
+ b = self._blender or self._settings.resolve_blender()
+ if not b or not Path(b).exists():
+ raise BlenderNotFoundError("Blender binary not found; set C3D_BINARIES__BLENDER=/path/to/blender")
+ return b
+
+ def run_wrapper(self, ws: Workspace, out_dir: Path, *, zones: dict[str, str] | None = None, blend: bool = True,
+ timeout_s: float | None = None) -> WrapperRun:
+ """Build the workspace in Blender, outputs into ``out_dir`` (``bpy_build.json``,
+ ``bpy_census.json``, ``census.glb``, ``scene.blend``); ``zones`` overrides the entry's ZONES."""
+ out_dir.mkdir(parents=True, exist_ok=True)
+ basis = ",".join(f"{v:g}" for row in glb_basis(LANGUAGE.value) for v in row)
+ cmd = [self.blender_binary(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",
+ "--scene", str(ws.root / ENTRY_REL), "--out", str(out_dir), "--basis", basis,
+ "--fps", str(FPS), "--frames", f"{frame_of(TIMES[0])},{frame_of(TIMES[-1])}",
+ "--rlimit-gb", str(self._settings.limits.bpy_rlimit_gb), "--seed", "0"]
+ if zones is not None:
+ cmd += ["--zones", json.dumps(zones)]
+ if not blend:
+ cmd.append("--no-blend")
+ report_path, facts_path = out_dir / "bpy_build.json", out_dir / "bpy_census.json"
+ for p in (report_path, facts_path):
+ p.unlink(missing_ok=True)
+ proc = run_subprocess(cmd, cwd=ws.root, env=blender_env(),
+ timeout_s=float(timeout_s or self._settings.limits.build_timeout_s))
+ report = read_json_or_none(report_path) or {}
+ result = compose_build_result(language=LANGUAGE.value, proc=proc, build_json=report_path, census_json=facts_path,
+ glb_path=out_dir / "census.glb", extra_paths={}, output_filter=strip_blender_noise,
+ publish=False)
+ if report.get("error_type") == "CensusGlbError":
+ result = result.model_copy(update={"harness_failure": True})
+ facts = read_json_or_none(facts_path) or {}
+ return WrapperRun(result=result, report=report, facts=facts)
+
+ def _measure(self, ws: Workspace, *, timeout_s: float | None, keep: tuple[str, ...] = ()
+ ) -> tuple[WrapperRun, GateReport | None, dict[str, Any]]:
+ """Wrapper + the census-GLB probe: (the Blender run, the ``scene_probe`` gate or ``None``
+ when nothing was built, the merged census). Every output but ``keep`` is wiped first."""
+ from codeverse3d.spatial.probes import PROBE_GATE, run_probe
+
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ ws.stage_artifacts(*[n for n in BUILD_OUTPUTS if n not in keep]).invalidate()
+ run = self.run_wrapper(ws, ws.artifacts, timeout_s=timeout_s)
+ if not run.result.ok:
+ return run, None, {}
+ probe, _, census = run_probe(ws, glb=ws.artifacts / "census.glb", facts=run.facts, timeout_s=timeout_s)
+ findings = stage_findings(run.report) + probe.findings
+ gate = GateReport.of(PROBE_GATE, findings, duration_ms=probe.duration_ms)
+ ws.write_json(ws.artifacts / "gates" / "scene_probe.json", gate)
+ if census:
+ census["language"] = LANGUAGE.value # the placement / frame hints speak bpy for it
+ ws.write_json(ws.artifacts / "census.json", census)
+ return run, gate, census
+
+ # ------------------------------------------------------------------ protocol
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ """Blender build + the census-GLB probe; ok iff the scene built and ``scene_probe`` passed
+ (a dropped zone, an env that raised or a Python driver fail it, with their file:line)."""
+ t0 = time.time()
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ if (missing := missing_entry(ws, self.language)) is not None:
+ ws.stage_artifacts(*[n for n in BUILD_OUTPUTS if n != "build.json"]).invalidate()
+ return missing
+ run, gate, census = self._measure(ws, timeout_s=timeout_s)
+ if gate is None:
+ res = run.result.model_copy(update={"duration_ms": int((time.time() - t0) * 1000)})
+ ws.write_json(ws.artifacts / "build.json", res)
+ return res
+ errors = sorted(gate.errors, key=lambda f: 0 if target_line(f.target) else 1)
+ first = errors[0] if errors else None
+ res = BuildResult(
+ ok=gate.passed, language=self.language.value, glb_path=None,
+ extra_paths={k: str(ws.artifacts / v) for k, v in (("census", "census.json"), ("census_glb", "census.glb"),
+ ("blend", "scene.blend"), ("scene_probe", "gates/scene_probe.json"))
+ if (ws.artifacts / v).is_file()},
+ stdout_tail=_summary_text(gate), stderr_tail=run.result.stderr_tail,
+ error_type=(first.data.get("kind") or first.gate) if first else "",
+ error_message=first.message if first else "",
+ error_file=target_file(first.target) if first else "",
+ error_line=target_line(first.target) if first else None,
+ duration_ms=int((time.time() - t0) * 1000), census=census, gates=[gate],
+ harness_failure=bool(first is not None and first.data.get("harness_failure")),
+ )
+ ws.write_json(ws.artifacts / "build.json", res)
+ return res
+
+ def probe(self, ws: Workspace, *, timeout_s: float = 60.0) -> SceneProbeResult:
+ """The build's own measurement (Blender run + census-GLB probe), without touching
+ ``build.json``: an offline scene has no cheaper way to load."""
+ from codeverse3d.spatial.probes import PROBE_GATE, probe_result
+
+ if not (ws.root / ENTRY_REL).is_file():
+ gate = GateReport.of(PROBE_GATE, [GateFinding(gate=PROBE_GATE, severity=Severity.ERROR, target=ENTRY_REL,
+ message=f"{ENTRY_REL} does not exist", fix_hint="re-run the assemble step")])
+ return probe_result(gate, {})
+ run, gate, census = self._measure(ws, timeout_s=max(timeout_s, float(self._settings.limits.build_timeout_s)),
+ keep=("build.json",))
+ if gate is None:
+ r = run.result
+ finding = GateFinding(gate=PROBE_GATE, severity=Severity.ERROR,
+ target=f"{r.error_file}:{r.error_line}" if r.error_line else (r.error_file or ENTRY_REL),
+ message=f"the scene did not build: {r.error_type}: {r.error_message}"[:1500],
+ data={"harness_failure": True} if r.harness_failure else {})
+ return probe_result(GateReport.of(PROBE_GATE, [finding]), {})
+ return probe_result(gate, census)
+
+ def assemble(self, ws: Workspace, plan: ScenePlan) -> AssembleResult:
+ """Build every zone module on disk once (isolated, no .blend) and write ``src/scene.py``
+ with the zones that built and the plan's cameras — scene_threejs's assembler semantics."""
+ return assemble(self, ws, plan)
+
+ def render_scene(self, ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None = None, orbit: bool = True,
+ times: Sequence[float] = TIMES, width: int = 1024, height: int = 576, sheet: bool = True) -> RenderSet:
+ raise NotImplementedError(
+ "scene_blender rendering is DESIGN phase 2 (render_bpy_scene.py + spatial/render_blender.py), not landed yet: "
+ "a scene_blender workspace builds and passes its geometry gates but cannot be rendered or judged")
+
+
+def stage_findings(report: dict[str, Any]) -> list[GateFinding]:
+ """The wrapper's isolated-stage failures as ``scene_probe`` findings: a zone / asset / env that
+ raised is an ERROR on its ``file:line`` (the zone is gone from the scene); a hero GLB that
+ would not import or is missing is a WARN on the file."""
+ from codeverse3d.spatial.probes import PROBE_GATE
+
+ out: list[GateFinding] = []
+ what = {"zone": "zone {name} raised {error_type}: {error_message} — it is dropped from the scene",
+ "asset": "asset {name} raised {error_type}: {error_message} — zones placing it get nothing",
+ "env": "src/env.py raised {error_type}: {error_message} — the scene built without its env (flat ground at z = 0)",
+ "scene": "create_scene raised {error_type}: {error_message}",
+ "hero": "hero {name} did not import: {error_type}: {error_message}"}
+ for e in report.get("errors") or []:
+ stage = str(e.get("stage"))
+ line = e.get("error_line")
+ target = f"{e.get('error_file')}:{line}" if line else str(e.get("error_file") or ENTRY_REL)
+ msg = what.get(stage, "{name} raised {error_type}: {error_message}").format(
+ name=e.get("name"), error_type=e.get("error_type"), error_message=str(e.get("error_message"))[:600])
+ src = str(e.get("error_source") or "")
+ out.append(GateFinding(gate=PROBE_GATE, severity=Severity.WARN if stage == "hero" else Severity.ERROR, target=target,
+ message=msg + (f" at: {src}" if src else ""), fix_hint="fix the quoted line; the rest of "
+ "the scene built without it" if stage != "hero" else "rebuild the hero asset",
+ data={"kind": f"{stage}_error", "stage": stage, "name": e.get("name"), "line": line}))
+ for w in report.get("warnings") or []:
+ out.append(GateFinding(gate=PROBE_GATE, severity=Severity.WARN, target="scene", message=str(w)[:500],
+ data={"kind": "build_warning"}))
+ return out
+
+
+# ===================================================================== assemble
+_ASSEMBLE_OUT = "assemble_probe"
+
+
+def assemble(runtime: SceneBlenderRuntime, ws: Workspace, plan: ScenePlan | None, *, probe: bool = True,
+ timeout_s: float | None = None) -> AssembleResult:
+ zones = [p.stem for p in module_files(ws, "zones")]
+ if not zones:
+ raise FileNotFoundError(f"no zone modules under {ws.src / 'zones'}")
+ assets = [p.stem for p in module_files(ws, "assets")]
+ heroes = [p.stem for p in hero_files(ws)]
+ cams = list(plan.cameras[:6]) if plan is not None and plan.cameras else [_fallback_camera(plan)]
+ warnings: list[str] = []
+ env_ok = (ws.src / "env.py").is_file()
+ if not env_ok:
+ warnings.append("src/env.py missing: scene assembled without env (flat ground at z = 0, no world or lamps)")
+ healthy, failed = list(zones), {}
+ census: dict[str, Any] = {}
+ out = ws.root / ENTRY_REL
+ if probe:
+ # the probe run needs an entry that lists every asset and hero; its zones come from --zones
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(render_scene_py([], assets, heroes, cams))
+ run = runtime.run_wrapper(ws, ws.artifacts / _ASSEMBLE_OUT, zones={z: to_pascal(z) for z in zones}, blend=False,
+ timeout_s=timeout_s)
+ if run.result.ok or run.report.get("zones_ok") is not None:
+ healthy = [z for z in zones if z in set(run.report.get("zones_ok") or [])]
+ failed = {z: str(m) for z, m in (run.report.get("zones_failed") or {}).items()}
+ else:
+ warnings.append(f"assembler probe did not run: {run.result.error_type}: {run.result.error_message}"[:300])
+ for e in run.report.get("errors") or []:
+ if e.get("stage") == "env":
+ env_ok = False
+ warnings.append(f"env.py failed in probe: {e.get('error_type')}: {e.get('error_message')}"[:300])
+ census = {k: run.facts[k] for k in ("lights", "fog", "background", "unique_tris", "instanced_tris") if k in run.facts}
+ if not healthy:
+ warnings.append("no zone module survived probing; scene.py assembled with zero zones")
+ out.write_text(render_scene_py(healthy, assets, heroes, cams, title=getattr(plan, "title", ""),
+ summary=getattr(plan, "summary", "")))
+ result = AssembleResult(scene_path=str(out), zones_included=healthy, zones_failed=failed, env_ok=env_ok,
+ cameras=cams, warnings=warnings, census=census)
+ ws.write_json(ws.artifacts / "assemble.json", result)
+ return result
+
+
+# ===================================================================== helpers
+def _summary_text(gate: GateReport) -> str:
+ lines = [f"scene_probe: {'ok' if gate.passed else 'FAILED'} ({len(gate.errors)} errors)"]
+ lines += [f" - {f.target or ''}: {f.message}"[:400] for f in gate.findings if f.severity != Severity.INFO][:12]
+ return "\n".join(lines)
+
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.py
index 7ac3e69c..0b96086a 100644
--- a/harness/codeverse3d/languages/scene_threejs/__init__.py
+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py
@@ -21,7 +21,7 @@ from codeverse3d.contracts.artifacts import (
from codeverse3d.contracts.common import ENTRY_FILE, Language
from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan, ZonePlan
from codeverse3d.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snake
-from codeverse3d.languages._common import line_of, missing_entry, ws_rel
+from codeverse3d.languages._common import line_of, missing_entry, target_file, target_line, ws_rel
from codeverse3d.languages._js_lint import (
ImportKind,
ImportVerdict,
@@ -779,7 +779,7 @@ class SceneThreeJsRuntime:
gates_dir = ws.artifacts / "gates"
ws.write_json(gates_dir / "scene_probe.json", probe)
ws.write_json(gates_dir / "shader_preflight.json", shaders)
- errors = sorted(probe.errors + shaders.errors, key=lambda f: 0 if _target_line(f.target) else 1)
+ errors = sorted(probe.errors + shaders.errors, key=lambda f: 0 if target_line(f.target) else 1)
first = errors[0] if errors else None
res = BuildResult(
ok=probe.passed and shaders.passed,
@@ -793,8 +793,8 @@ class SceneThreeJsRuntime:
stdout_tail=_summary_text(probe, shaders),
error_type=(first.data.get("kind") or first.gate) if first else "",
error_message=first.message if first else "",
- error_file=_target_file(first.target) if first else "",
- error_line=_target_line(first.target) if first else None,
+ error_file=target_file(first.target) if first else "",
+ error_line=target_line(first.target) if first else None,
duration_ms=int((time.time() - t0) * 1000),
census=census,
gates=[probe, shaders],
@@ -814,16 +814,3 @@ def _summary_text(probe: GateReport, shaders: GateReport) -> str:
lines += [f" - {f.target or ''}: {f.message}"[:400] for f in shaders.findings if f.severity != Severity.INFO][:12]
return "\n".join(lines)
-
-def _target_file(target: str | None) -> str:
- if not target:
- return ""
- head, sep, tail = target.rpartition(":")
- return head if sep and tail.isdigit() else target
-
-
-def _target_line(target: str | None) -> int | None:
- if not target:
- return None
- _, sep, tail = target.rpartition(":")
- return int(tail) if sep and tail.isdigit() else None
diff --git a/harness/codeverse3d/languages/wrappers/_census_glb.py b/harness/codeverse3d/languages/wrappers/_census_glb.py
new file mode 100644
index 00000000..398bc6c6
--- /dev/null
+++ b/harness/codeverse3d/languages/wrappers/_census_glb.py
@@ -0,0 +1,389 @@
+"""The scene_blender census GLB — executed BY Blender (``run_bpy_scene.py``), never imported by the harness.
+
+The geometry gates are the JS ones (``probe_scene.mjs`` → ``host_census`` + ``host_placement``), so a
+Blender scene reaches them as a GLB the harness writes itself from the EVALUATED depsgraph — what
+renders: modifiers, geometry nodes and instances included. The official glTF exporter is not usable
+for this (DESIGN §1.4: it silently drops geometry-nodes instances, and with ``export_gn_mesh`` it did
+not finish in 10 min on 73 k grass blades; this writer: 0.1–0.4 s). Geometry, names, base colour
+and custom properties only: the file is an instrument for gates, never a picture.
+
+Layout (what the census and the placement table read):
+
+* root nodes = env objects (whatever is not in a zone collection), by object name — ``backdrop.mjs``
+ classifies ``Ground`` / ``Terrain`` / ``Water`` / ``Sky…`` by name, so names are carried verbatim;
+* one root node per ZONE collection, named for it; its children = the zone's root objects, their
+ parent chains as child nodes (group nodes carry no transform: every mesh node holds its world
+ matrix, so an Empty's rotation can never be applied twice);
+* a collection-instance Empty = a node whose children are one mesh node per instanced object, all
+ sharing one glTF mesh per source mesh — a clone per placed asset, which ``host_placement`` checks;
+* any other instance cloud (geometry nodes, particles, dupli-verts/faces) = one
+ ``EXT_mesh_gpu_instancing`` node per (instancer, source mesh) — an ``InstancedMesh`` in three.js,
+ counted as instances and exempt from per-asset placement exactly like scatter is today;
+* a mesh every material of which is volume-only (a fog box) is not written: it is not matter, and
+ the fog is reported from bpy instead (``run_bpy_scene.scene_facts``);
+* custom properties of str/int/float/bool value → node ``extras`` → three.js ``userData`` (so
+ ``obj["placement"] = "free"`` exempts a deliberately airborne thing, as ``userData.placement`` does);
+* the scene's ``extras.c3d_cameras`` carries the harness cameras in the GLB frame — the adapter
+ (``runtime_js/lib/glb_scene.mjs``) hands them to the host.
+
+Frame: ``basis`` (3×3 rows, from ``conventions.glb_basis`` via the wrapper's argv) takes a Blender
+vector into the GLB frame (Y-up, +Z front); nothing here restates it.
+"""
+
+from __future__ import annotations
+
+import json
+import struct
+import time
+from typing import Any
+
+import numpy as np
+
+MEASURABLE_TYPES = ("MESH", "CURVE", "SURFACE", "FONT", "META")
+_FLOAT, _UINT = 5126, 5125
+_ARRAY_BUFFER, _ELEMENT_ARRAY_BUFFER = 34962, 34963
+
+
+# ----------------------------------------------------------------------------- material facts
+def _active_output(tree: Any, kind: str) -> Any:
+ outs = [n for n in tree.nodes if n.bl_idname == kind]
+ return next((n for n in outs if getattr(n, "is_active_output", False)), outs[0] if outs else None)
+
+
+def is_volume_material(mat: Any) -> bool:
+ """A material whose active output feeds Volume and not Surface: fog, not matter."""
+ tree = getattr(mat, "node_tree", None) if mat is not None else None
+ if tree is None:
+ return False
+ out = _active_output(tree, "ShaderNodeOutputMaterial")
+ if out is None:
+ return False
+ return bool(out.inputs["Volume"].is_linked and not out.inputs["Surface"].is_linked)
+
+
+def is_volume_only(obj: Any) -> bool:
+ """Every material slot of ``obj`` is a volume material (and it has at least one)."""
+ mats = [s.material for s in getattr(obj, "material_slots", ())]
+ return bool(mats) and all(is_volume_material(m) for m in mats)
+
+
+def _principled(mat: Any) -> Any:
+ tree = getattr(mat, "node_tree", None) if mat is not None else None
+ if tree is None:
+ return None
+ return next((n for n in tree.nodes if n.bl_idname == "ShaderNodeBsdfPrincipled"), None)
+
+
+def _input_value(node: Any, name: str, default: Any) -> Any:
+ sock = node.inputs.get(name) if node is not None else None
+ if sock is None or sock.is_linked:
+ return default
+ try:
+ return sock.default_value
+ except AttributeError:
+ return default
+
+
+# ----------------------------------------------------------------------------- math
+def _quaternions(rot: np.ndarray) -> np.ndarray:
+ """(n, 3, 3) rotation matrices → (n, 4) quaternions (x, y, z, w), Shepperd's method."""
+ n = rot.shape[0]
+ q = np.empty((n, 4), np.float64)
+ tr = rot[:, 0, 0] + rot[:, 1, 1] + rot[:, 2, 2]
+ cases = np.stack([tr, rot[:, 0, 0], rot[:, 1, 1], rot[:, 2, 2]], 1).argmax(1)
+ for case in range(4):
+ m = cases == case
+ if not m.any():
+ continue
+ r = rot[m]
+ if case == 0:
+ s = np.sqrt(np.maximum(tr[m] + 1.0, 1e-12)) * 2
+ q[m] = np.stack([(r[:, 2, 1] - r[:, 1, 2]) / s, (r[:, 0, 2] - r[:, 2, 0]) / s,
+ (r[:, 1, 0] - r[:, 0, 1]) / s, 0.25 * s], 1)
+ else:
+ i = case - 1
+ j, k = (i + 1) % 3, (i + 2) % 3
+ s = np.sqrt(np.maximum(1.0 + r[:, i, i] - r[:, j, j] - r[:, k, k], 1e-12)) * 2
+ out = np.empty((r.shape[0], 4))
+ out[:, i] = 0.25 * s
+ out[:, j] = (r[:, j, i] + r[:, i, j]) / s
+ out[:, k] = (r[:, k, i] + r[:, i, k]) / s
+ out[:, 3] = (r[:, k, j] - r[:, j, k]) / s
+ q[m] = out
+ return q / np.linalg.norm(q, axis=1, keepdims=True)
+
+
+def _trs(mats: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """(n, 4, 4) GLB-frame matrices → translations, quaternions, scales (a mirror flips one scale)."""
+ t = mats[:, :3, 3]
+ lin = mats[:, :3, :3]
+ s = np.linalg.norm(lin, axis=1) # column norms: L = R · diag(s)
+ s = np.where(s < 1e-12, 1e-12, s)
+ r = lin / s[:, None, :]
+ neg = np.linalg.det(r) < 0
+ if neg.any():
+ s[neg, 0] *= -1
+ r[neg, :, 0] *= -1
+ return t, _quaternions(r), s
+
+
+# ----------------------------------------------------------------------------- writer
+class _Writer:
+ def __init__(self, basis: np.ndarray) -> None:
+ self.b3 = basis
+ self.b4 = np.eye(4)
+ self.b4[:3, :3] = basis
+ self.buf = bytearray()
+ self.views: list[dict[str, Any]] = []
+ self.accessors: list[dict[str, Any]] = []
+ self.meshes: list[dict[str, Any]] = []
+ self.mesh_ix: dict[Any, int | None] = {}
+ self.mesh_tris: dict[int, int] = {}
+ self.materials: list[dict[str, Any]] = []
+ self.mat_ix: dict[str, int] = {}
+ self.nodes: list[dict[str, Any]] = []
+ self.roots: list[int] = []
+ self.group_ix: dict[tuple[str, ...], int] = {}
+
+ # -- buffers
+ def add(self, arr: np.ndarray, *, target: int | None = None, comp: int = _FLOAT, typ: str = "VEC3") -> int:
+ a = np.ascontiguousarray(arr)
+ off = len(self.buf)
+ self.buf.extend(a.tobytes())
+ self.buf.extend(b"\0" * (-len(self.buf) % 4))
+ view: dict[str, Any] = {"buffer": 0, "byteOffset": off, "byteLength": a.nbytes}
+ if target:
+ view["target"] = target
+ self.views.append(view)
+ acc: dict[str, Any] = {"bufferView": len(self.views) - 1, "componentType": comp, "count": int(a.shape[0]), "type": typ}
+ if target == _ARRAY_BUFFER:
+ acc["min"] = a.min(0).tolist()
+ acc["max"] = a.max(0).tolist()
+ self.accessors.append(acc)
+ return len(self.accessors) - 1
+
+ def material(self, mat: Any) -> int:
+ key = mat.name if mat is not None else "_none"
+ if key not in self.mat_ix:
+ bsdf = _principled(mat)
+ col = list(_input_value(bsdf, "Base Color", (0.8, 0.8, 0.8, 1.0)))[:4]
+ col = [min(1.0, max(0.0, float(c))) for c in col] + [1.0] * (4 - len(col))
+ pbr = {"baseColorFactor": col,
+ "metallicFactor": min(1.0, max(0.0, float(_input_value(bsdf, "Metallic", 0.0)))),
+ "roughnessFactor": min(1.0, max(0.0, float(_input_value(bsdf, "Roughness", 0.5))))}
+ self.mat_ix[key] = len(self.materials)
+ self.materials.append({"name": key, "pbrMetallicRoughness": pbr})
+ return self.mat_ix[key]
+
+ def mesh(self, key: Any, me: Any, slots: list[Any]) -> int | None:
+ """One glTF mesh per source mesh datablock (``key``); ``None`` for an empty one."""
+ if key in self.mesh_ix:
+ return self.mesh_ix[key]
+ me.calc_loop_triangles()
+ nv, nt = len(me.vertices), len(me.loop_triangles)
+ if nt == 0 or nv == 0:
+ self.mesh_ix[key] = None
+ return None
+ co = np.empty(nv * 3, np.float32)
+ me.vertices.foreach_get("co", co)
+ co = (co.reshape(-1, 3).astype(np.float64) @ self.b3.T).astype(np.float32)
+ tri = np.empty(nt * 3, np.uint32)
+ me.loop_triangles.foreach_get("vertices", tri)
+ tri = tri.reshape(-1, 3)
+ mi = np.empty(nt, np.int32)
+ me.loop_triangles.foreach_get("material_index", mi)
+ pos = self.add(co, target=_ARRAY_BUFFER)
+ prims = []
+ for m in np.unique(mi):
+ idx = self.add(tri[mi == m].reshape(-1), target=_ELEMENT_ARRAY_BUFFER, comp=_UINT, typ="SCALAR")
+ slot = slots[int(m)] if 0 <= int(m) < len(slots) else None
+ prims.append({"attributes": {"POSITION": pos}, "indices": idx, "material": self.material(slot)})
+ self.meshes.append({"name": me.name, "primitives": prims})
+ ix = len(self.meshes) - 1
+ self.mesh_ix[key] = ix
+ self.mesh_tris[ix] = nt
+ return ix
+
+ # -- nodes
+ def glb_matrix(self, mw: Any) -> np.ndarray:
+ return self.b4 @ np.array(mw, np.float64) @ self.b4.T
+
+ def node(self, node: dict[str, Any], path: tuple[str, ...]) -> int:
+ """Append ``node`` under the group node of ``path`` (a root when ``path`` is empty)."""
+ self.nodes.append(node)
+ i = len(self.nodes) - 1
+ if path:
+ self.nodes[self.group(path)].setdefault("children", []).append(i)
+ else:
+ self.roots.append(i)
+ return i
+
+ def group(self, path: tuple[str, ...], extras: dict[str, Any] | None = None) -> int:
+ if path not in self.group_ix:
+ node: dict[str, Any] = {"name": path[-1]}
+ if extras:
+ node["extras"] = extras
+ self.group_ix[path] = self.node(node, path[:-1])
+ return self.group_ix[path]
+
+ def glb(self, scene_extras: dict[str, Any]) -> bytes:
+ g: dict[str, Any] = {
+ "asset": {"version": "2.0", "generator": "codeverse3d census_glb"},
+ "scene": 0, "scenes": [{"nodes": self.roots, "extras": scene_extras}],
+ "nodes": self.nodes, "meshes": self.meshes, "materials": self.materials,
+ "accessors": self.accessors, "bufferViews": self.views, "buffers": [{"byteLength": len(self.buf)}],
+ }
+ if any("extensions" in n for n in self.nodes):
+ g["extensionsUsed"] = ["EXT_mesh_gpu_instancing"]
+ js = json.dumps(g, separators=(",", ":")).encode()
+ js += b" " * (-len(js) % 4)
+ head = struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(js) + 8 + len(self.buf))
+ return (head + struct.pack("<II", len(js), 0x4E4F534A) + js
+ + struct.pack("<II", len(self.buf), 0x004E4942) + bytes(self.buf))
+
+
+def extras_of(obj: Any) -> dict[str, Any]:
+ """Custom properties a gate can read (``placement = 'free'``); IDProperty groups / arrays dropped."""
+ out: dict[str, Any] = {}
+ for k in obj.keys(): # noqa: SIM118 — a bpy ID is not iterable over its custom properties
+ v = obj[k]
+ if isinstance(v, (str, int, float, bool)) and not k.startswith("_"):
+ out[k] = v
+ return out
+
+
+def _chain(obj: Any) -> list[Any]:
+ out = []
+ while obj is not None:
+ out.append(obj)
+ obj = obj.parent
+ return out[::-1]
+
+
+def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: dict[str, str],
+ cameras: list[dict[str, Any]]) -> dict[str, Any]:
+ """Write the census GLB of the current (t = 0) state to ``path``; return its stats.
+
+ ``zones`` maps a zone COLLECTION name to itself for every zone the wrapper built (the node
+ name); every object in one of them (recursively) hangs under that zone's node."""
+ t0 = time.perf_counter()
+ w = _Writer(np.array(basis, np.float64))
+ zone_of: dict[str, str] = {}
+ for cname in zones:
+ coll = bpy.data.collections.get(cname)
+ if coll is not None:
+ for o in coll.all_objects:
+ zone_of.setdefault(o.name, cname)
+
+ def path_of(obj: Any) -> tuple[str, ...]:
+ chain = _chain(obj)
+ zone = zone_of.get(chain[0].name)
+ return ((zone,) if zone else ()) + tuple(o.name for o in chain)
+
+ def ensure_groups(obj: Any, *, own: bool = False) -> tuple[str, ...]:
+ """Group nodes for the ancestors of ``obj`` (+ ``obj`` itself when ``own``), top down so each
+ carries its object's custom properties; returns the path ``obj``'s own node hangs under."""
+ chain = _chain(obj)
+ zone = zone_of.get(chain[0].name)
+ base = (zone,) if zone else ()
+ upto = chain if own else chain[:-1]
+ for i, o in enumerate(upto):
+ w.group(base + tuple(x.name for x in chain[: i + 1]), extras_of(o))
+ return path_of(obj) if own else path_of(obj)[:-1]
+
+ stats: dict[str, Any] = {"unique_tris": 0, "instanced_tris": 0, "nodes": 0, "meshes": 0, "instances": 0,
+ "clouds": 0, "volumes_skipped": []}
+ dg = bpy.context.evaluated_depsgraph_get()
+ clouds: dict[tuple[tuple[str, ...], Any], tuple[int | None, str, list[np.ndarray]]] = {}
+ for zone in zones: # an empty zone is still a group the census can see
+ w.group((zone,), extras_of(bpy.data.collections[zone]) if zone in bpy.data.collections else None)
+ # an object that hosts an instance cloud is its own group (its mesh + the cloud = one row)
+ hosts = {inst.parent.original.name for inst in dg.object_instances
+ if inst.is_instance and inst.parent is not None and inst.parent.original.instance_type != "COLLECTION"}
+ for inst in dg.object_instances:
+ ob = inst.object
+ if ob.type != "MESH":
+ continue
+ if inst.is_instance:
+ host = inst.parent.original if inst.parent is not None else None
+ if host is None or host.hide_render or is_volume_only(ob):
+ continue
+ ix = w.mesh(ob.data.as_pointer(), ob.data, [s.material for s in ob.material_slots])
+ if ix is None:
+ continue
+ if host.instance_type == "COLLECTION": # a placed asset: one clone node per instanced mesh
+ m = w.glb_matrix(inst.matrix_world)
+ w.node({"name": ob.name, "mesh": ix, "matrix": m.T.reshape(-1).tolist()}, ensure_groups(host, own=True))
+ stats["instanced_tris"] += w.mesh_tris[ix]
+ continue
+ key = (path_of(host), ob.data.as_pointer()) # Blender-frame matrices, converted in one batch below
+ clouds.setdefault(key, (ix, ob.name, []))[2].append(np.array(inst.matrix_world, np.float32))
+ continue
+ orig = ob.original
+ if orig.hide_render or is_volume_only(orig):
+ if is_volume_only(orig):
+ stats["volumes_skipped"].append(orig.name)
+ continue
+ ix = w.mesh(("obj", orig.name), ob.data, [s.material for s in ob.material_slots])
+ if ix is None:
+ continue
+ # a mesh with children is its own group (one placement row), its geometry a node inside it
+ under = ensure_groups(orig, own=bool(orig.children) or orig.name in hosts)
+ node = {"name": orig.name, "mesh": ix, "matrix": w.glb_matrix(ob.matrix_world).T.reshape(-1).tolist()}
+ if ex := extras_of(orig):
+ node["extras"] = ex
+ w.node(node, under)
+ stats["instanced_tris"] += w.mesh_tris[ix]
+ for (host_path, _), (ix, oname, mats) in clouds.items():
+ if ix is None:
+ continue
+ t, q, s = _trs(w.b4 @ np.stack(mats).astype(np.float64) @ w.b4.T)
+ ext = {"TRANSLATION": w.add(t.astype(np.float32)), "ROTATION": w.add(q.astype(np.float32), typ="VEC4"),
+ "SCALE": w.add(s.astype(np.float32))}
+ w.group(host_path)
+ w.node({"name": f"{oname}_cloud", "mesh": ix, "extensions": {"EXT_mesh_gpu_instancing": {"attributes": ext}}},
+ host_path)
+ stats["instances"] += len(mats)
+ stats["clouds"] += 1
+ stats["instanced_tris"] += w.mesh_tris[ix] * len(mats)
+ _write_other_types(dg, w, stats, ensure_groups)
+ stats["unique_tris"] = sum(w.mesh_tris.values())
+ stats["nodes"], stats["meshes"] = len(w.nodes), len(w.meshes)
+ data = w.glb({"c3d_cameras": [_glb_camera(c, w.b3) for c in cameras]})
+ with open(path, "wb") as fh:
+ fh.write(data)
+ stats["bytes"] = len(data)
+ stats["ms"] = int((time.perf_counter() - t0) * 1000)
+ return stats
+
+
+def _write_other_types(dg: Any, w: _Writer, stats: dict[str, Any], ensure_groups: Any) -> None:
+ """Curves, text, surfaces and metaballs that stayed their own type after evaluation."""
+ for inst in dg.object_instances:
+ ob = inst.object
+ if inst.is_instance or ob.type == "MESH" or ob.type not in MEASURABLE_TYPES:
+ continue
+ orig = ob.original
+ if orig.hide_render or is_volume_only(orig):
+ continue
+ try:
+ me = ob.to_mesh()
+ except RuntimeError:
+ continue
+ try:
+ ix = w.mesh(("obj", orig.name), me, [s.material for s in ob.material_slots])
+ finally:
+ ob.to_mesh_clear()
+ if ix is None:
+ continue
+ node = {"name": orig.name, "mesh": ix, "matrix": w.glb_matrix(ob.matrix_world).T.reshape(-1).tolist()}
+ w.node(node, ensure_groups(orig, own=bool(orig.children)))
+ stats["instanced_tris"] += w.mesh_tris[ix]
+
+
+def _glb_camera(c: dict[str, Any], b3: np.ndarray) -> dict[str, Any]:
+ """A harness camera (Blender frame: ``location`` / ``look_at``, vertical ``fov``) as the host's spec."""
+ pos = (b3 @ np.array(c["location"], np.float64)).tolist()
+ look = (b3 @ np.array(c["look_at"], np.float64)).tolist()
+ return {"name": str(c["name"]), "position": [round(v, 5) for v in pos], "lookAt": [round(v, 5) for v in look],
+ "fov": float(c.get("fov", 50.0))}
diff --git a/harness/codeverse3d/languages/wrappers/_wrapper_common.py b/harness/codeverse3d/languages/wrappers/_wrapper_common.py
index c417ff24..2e2d039a 100644
--- a/harness/codeverse3d/languages/wrappers/_wrapper_common.py
+++ b/harness/codeverse3d/languages/wrappers/_wrapper_common.py
@@ -132,12 +132,14 @@ def run_script(script_path: str) -> tuple[BaseException | None, dict[str, Any] |
sys.argv = saved_argv
-def write_report(out_dir: str, report: dict[str, Any], census: dict[str, Any], t0: float) -> None:
- """census.json + build.json, atomically; a failure's traceback also goes to stderr, where
- the runtime's ``stderr_tail`` (and so the repair prompt) picks it up."""
+def write_report(out_dir: str, report: dict[str, Any], census: dict[str, Any], t0: float, *,
+ names: tuple[str, str] = ("build.json", "census.json")) -> None:
+ """census.json + build.json (``names``: the report's and the census's file names), atomically;
+ a failure's traceback also goes to stderr, where the runtime's ``stderr_tail`` (and so the
+ repair prompt) picks it up."""
report["duration_ms"] = int((time.monotonic() - t0) * 1000)
- _write_json_atomic(os.path.join(out_dir, "census.json"), census)
- _write_json_atomic(os.path.join(out_dir, "build.json"), report)
+ _write_json_atomic(os.path.join(out_dir, names[1]), census)
+ _write_json_atomic(os.path.join(out_dir, names[0]), report)
if report.get("traceback"):
print(report["traceback"], file=sys.stderr, end="")
diff --git a/harness/codeverse3d/languages/wrappers/run_bpy_scene.py b/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
new file mode 100644
index 00000000..4681d2e0
--- /dev/null
+++ b/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
@@ -0,0 +1,524 @@
+"""Blender SCENE build wrapper (scene_blender) — executed BY Blender, never imported by the harness.
+
+ blender -b --factory-startup --python run_bpy_scene.py -- \
+ --scene /abs/src/scene.py --out /abs/artifacts --basis 1,0,0,0,0,1,0,-1,0 \
+ [--fps 30] [--frames 1,46] [--rlimit-gb 12] [--seed 0] [--zones '{"a": "A"}'] [--no-blend]
+
+What it does (in order), DESIGN §3.3:
+ 1. caps the address space, empties the factory scene (and its world), metric units, ``fps`` and
+ the frame range (harness-owned), seeds ``random`` / numpy / mathutils.noise;
+ 2. runs ``src/scene.py`` (assembled by the harness: ``ZONES`` / ``ASSETS`` / ``HEROES`` /
+ ``CAMERAS`` data; a single-file scene defines ``create_scene(ctx)`` instead) — a failure here
+ is the build's error, mapped to ``src/<file>:<line>``;
+ 3. builds the ctx (``SceneContext``) and runs, EACH IN ITS OWN try/except, ``env.build_env``,
+ every hero import (``public/assets/<snake>.glb``), every ``assets.<snake>.build_<snake>`` and
+ every ``zones.<snake>.build``: a stage that raises is reported with its ``file:line`` and
+ whatever it created is removed — the zone is DROPPED, the rest of the scene still builds and
+ is measured (the assembler's probe semantics);
+ 4. hides the asset sources (they render through their collection instances), creates the
+ harness cameras (plan fov is VERTICAL, as in three.js), sets frame 1 (t = 0);
+ 5. writes the bpy facts the GLB cannot carry (``bpy_census.json``: lights, fog, background,
+ drivers that will not run, unique vs instanced triangles), the census GLB (``_census_glb``)
+ and the compressed ``scene.blend`` the render driver opens;
+ 6. writes ``bpy_build.json`` and exits 0.
+
+``--zones`` overrides ``ZONES`` (the assembler's probe: every zone module on disk). Exit codes: 0 =
+reported (even if the script failed); 2 = wrapper bug (no report). Standalone: the sibling modules
+are imported from this file's own directory.
+"""
+
+from __future__ import annotations
+
+import argparse
+import contextlib
+import importlib
+import json
+import math
+import os
+import random
+import sys
+import time
+from typing import Any
+
+sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
+from _census_glb import ( # noqa: E402 (siblings)
+ is_volume_material,
+ is_volume_only,
+ write_census_glb,
+)
+from _wrapper_common import ( # noqa: E402
+ exit_after,
+ map_exception,
+ new_report,
+ run_script,
+ seed_everything,
+ wrapper_argv,
+ write_report,
+)
+from run_bpy import MEMORY_HINT, clear_scene, render_fingerprint # noqa: E402
+
+REPORT_NAME, FACTS_NAME = "bpy_build.json", "bpy_census.json"
+GLB_NAME, BLEND_NAME = "census.glb", "scene.blend"
+#: the workspace packages a scene imports from ``src/`` (purged before every run: never a stale module)
+PACKAGES = ("env", "zones", "assets", "lib")
+ASSETS_COLLECTION, CAMERAS_COLLECTION = "_Assets", "_Cameras"
+_ERROR_KEYS = ("error_type", "error_message", "error_file", "error_line", "error_source")
+
+
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ p = argparse.ArgumentParser(prog="run_bpy_scene.py")
+ p.add_argument("--scene", required=True)
+ p.add_argument("--out", required=True)
+ p.add_argument("--basis", required=True, help="9 numbers, row-major: Blender frame -> GLB frame")
+ p.add_argument("--fps", type=int, default=30)
+ p.add_argument("--frames", default="1,46", help="first,last frame of the harness frame range")
+ p.add_argument("--rlimit-gb", type=float, default=12.0)
+ p.add_argument("--seed", type=int, default=0)
+ p.add_argument("--zones", default=None, help='JSON {"snake": "Pascal"} that overrides ZONES')
+ p.add_argument("--no-blend", action="store_true")
+ return p.parse_args(argv)
+
+
+class SceneContext:
+ """What ``build_env`` / ``build_<asset>`` / zone ``build`` receive (DESIGN §3.2): data, never verbs.
+
+ ``scene`` the bpy Scene (render settings are harness-owned) · ``collection`` the Collection this
+ builder links into (the zone's own, pre-created and active) · ``height_at(x, y) -> z`` the
+ env's ground · ``env`` what ``build_env`` returned · ``assets`` ``{snake: Collection}`` (procedural
+ assets and imported heroes) · ``rng(seed)`` the only randomness · ``fps`` / ``times`` the
+ harness's frame clock: ``frame(t) = 1 + round(t * fps)``."""
+
+ def __init__(self, scene: Any, fps: int, times: tuple[float, ...]) -> None:
+ self.scene = scene
+ self.collection = scene.collection
+ self.height_at = _flat
+ self.env: dict[str, Any] = {}
+ self.assets: dict[str, Any] = {}
+ self.fps = fps
+ self.times = times
+
+ @staticmethod
+ def rng(seed: int = 0) -> random.Random:
+ return random.Random(seed)
+
+ def frame(self, t: float) -> int:
+ return 1 + round(t * self.fps)
+
+
+def _flat(x: float, y: float) -> float:
+ return 0.0
+
+
+# ----------------------------------------------------------------------------- scene prep
+def prepare_scene(bpy: Any, fps: int, frames: tuple[int, int]) -> None:
+ clear_scene(bpy)
+ for world in list(bpy.data.worlds): # a scene's world is the env's to build (no factory grey)
+ bpy.data.worlds.remove(world)
+ scene = bpy.context.scene
+ scene.render.fps = fps
+ scene.render.fps_base = 1.0
+ scene.frame_start, scene.frame_end = frames
+ scene.frame_set(frames[0])
+
+
+def purge_workspace_modules() -> None:
+ for name in [m for m in sys.modules if m.split(".")[0] in PACKAGES]:
+ del sys.modules[name]
+ importlib.invalidate_caches()
+
+
+def layer_collection(view_layer: Any, coll: Any) -> Any:
+ stack = [view_layer.layer_collection]
+ while stack:
+ lc = stack.pop()
+ if lc.collection == coll:
+ return lc
+ stack.extend(lc.children)
+ return None
+
+
+def new_collection(bpy: Any, name: str, parent: Any) -> Any:
+ coll = bpy.data.collections.new(name)
+ parent.children.link(coll)
+ return coll
+
+
+def activate(bpy: Any, coll: Any) -> None:
+ """Make ``coll`` the active collection, so ``bpy.ops`` primitives land in it."""
+ lc = layer_collection(bpy.context.view_layer, coll)
+ if lc is not None:
+ bpy.context.view_layer.active_layer_collection = lc
+
+
+class Stages:
+ """Runs one builder at a time; a raise is recorded with its ``src/`` file:line and everything
+ the builder created is removed again (objects and collections)."""
+
+ def __init__(self, bpy: Any, script: str, report: dict[str, Any]) -> None:
+ self.bpy, self.script, self.report = bpy, script, report
+
+ def run(self, stage: str, name: str, default_file: str, fn: Any) -> tuple[Any, bool]:
+ bpy = self.bpy
+ objs = {o.as_pointer() for o in bpy.data.objects}
+ colls = {c.as_pointer() for c in bpy.data.collections}
+ try:
+ return fn(), True
+ except BaseException as e: # noqa: BLE001 — a builder's failure is a finding, never the wrapper's
+ if isinstance(e, KeyboardInterrupt):
+ raise
+ info = map_exception(e, self.script, memory=MEMORY_HINT)
+ entry = {"stage": stage, "name": name, **{k: info[k] for k in _ERROR_KEYS},
+ "traceback": info["traceback"][-2500:]}
+ entry["error_file"] = entry["error_file"] or default_file
+ self.report["errors"].append(entry)
+ print(info["traceback"], file=sys.stderr, end="")
+ with contextlib.suppress(Exception):
+ if bpy.context.object and bpy.context.object.mode != "OBJECT":
+ bpy.ops.object.mode_set(mode="OBJECT")
+ for o in [o for o in bpy.data.objects if o.as_pointer() not in objs]:
+ bpy.data.objects.remove(o, do_unlink=True)
+ for c in [c for c in bpy.data.collections if c.as_pointer() not in colls]:
+ bpy.data.collections.remove(c)
+ return None, False
+
+
+# ----------------------------------------------------------------------------- stages
+def build_env(bpy: Any, ctx: SceneContext, stages: Stages, src: str) -> None:
+ if not os.path.isfile(os.path.join(src, "env.py")):
+ return
+
+ def run() -> None:
+ mod = importlib.import_module("env")
+ if callable(getattr(mod, "height_at", None)):
+ ctx.height_at = mod.height_at
+ if not callable(getattr(mod, "build_env", None)):
+ raise AttributeError("src/env.py defines no build_env(ctx)")
+ activate(bpy, bpy.context.scene.collection)
+ ctx.collection = bpy.context.scene.collection
+ out = mod.build_env(ctx)
+ ctx.env = out if isinstance(out, dict) else {}
+
+ stages.run("env", "env", "src/env.py", run)
+
+
+def build_assets(bpy: Any, ctx: SceneContext, stages: Stages, ws: str, heroes: dict[str, str],
+ assets: dict[str, str], report: dict[str, Any]) -> Any:
+ root = new_collection(bpy, ASSETS_COLLECTION, bpy.context.scene.collection)
+ for snake, pascal in heroes.items():
+ glb = os.path.join(ws, "public", "assets", f"{snake}.glb")
+ if not os.path.isfile(glb):
+ report["warnings"].append(f"hero public/assets/{snake}.glb is missing: zones placing it get no ctx.assets['{snake}']")
+ continue
+
+ def load(snake: str = snake, pascal: str = pascal, glb: str = glb) -> Any:
+ coll = new_collection(bpy, pascal, root)
+ activate(bpy, coll)
+ bpy.ops.import_scene.gltf(filepath=glb)
+ return coll
+
+ coll, ok = stages.run("hero", snake, f"public/assets/{snake}.glb", load)
+ if ok:
+ ctx.assets[snake] = coll
+ for snake, pascal in assets.items():
+ def make(snake: str = snake, pascal: str = pascal) -> Any:
+ mod = importlib.import_module(f"assets.{snake}")
+ fn = getattr(mod, f"build_{snake}", None)
+ if not callable(fn):
+ raise AttributeError(f"src/assets/{snake}.py defines no build_{snake}(ctx, variant=0)")
+ coll = new_collection(bpy, pascal, root)
+ activate(bpy, coll)
+ ctx.collection = coll
+ out = fn(ctx)
+ if isinstance(out, bpy.types.Collection) and out != coll:
+ if out.name not in root.children:
+ root.children.link(out)
+ for parent in (bpy.context.scene.collection,):
+ if out.name in parent.children:
+ parent.children.unlink(out)
+ return out
+ return coll
+
+ coll, ok = stages.run("asset", snake, f"src/assets/{snake}.py", make)
+ if ok:
+ ctx.assets[snake] = coll
+ return root
+
+
+def build_zones(bpy: Any, ctx: SceneContext, stages: Stages, zones: dict[str, str], report: dict[str, Any]) -> dict[str, str]:
+ """Build every zone; returns ``{snake: collection name}`` of the zones that built."""
+ scene_coll = bpy.context.scene.collection
+ built: dict[str, str] = {}
+ for snake, pascal in zones.items():
+ def make(snake: str = snake, pascal: str = pascal) -> str:
+ mod = importlib.import_module(f"zones.{snake}")
+ if not callable(getattr(mod, "build", None)):
+ raise AttributeError(f"src/zones/{snake}.py defines no build(ctx)")
+ coll = new_collection(bpy, pascal, scene_coll)
+ activate(bpy, coll)
+ ctx.collection = coll
+ out = mod.build(ctx)
+ if isinstance(out, bpy.types.Collection) and out != coll:
+ if out.name not in scene_coll.children and not any(out.name in c.children for c in bpy.data.collections):
+ scene_coll.children.link(out)
+ if not coll.all_objects:
+ bpy.data.collections.remove(coll)
+ coll = out
+ if coll.name != pascal:
+ report["warnings"].append(f"zone {snake}: its collection is named {coll.name!r}, not {pascal!r}")
+ return coll.name
+
+ name, ok = stages.run("zone", snake, f"src/zones/{snake}.py", make)
+ if ok:
+ built[snake] = name
+ else:
+ report["zones_failed"][snake] = report["errors"][-1]["error_message"][:600]
+ return built
+
+
+def add_cameras(bpy: Any, cams: list[dict[str, Any]], report: dict[str, Any]) -> None:
+ from mathutils import Vector # noqa: PLC0415 — Blender-only
+
+ coll = new_collection(bpy, CAMERAS_COLLECTION, bpy.context.scene.collection)
+ first = None
+ for c in cams:
+ data = bpy.data.cameras.new(str(c["name"]))
+ data.sensor_fit = "VERTICAL" # the plan's fov is vertical, as three.js's PerspectiveCamera.fov
+ data.angle_y = math.radians(float(c.get("fov", 50.0)))
+ data.clip_start, data.clip_end = 0.05, 20000.0
+ ob = bpy.data.objects.new(str(c["name"]), data)
+ coll.objects.link(ob)
+ ob.location = Vector(c["location"])
+ ob.rotation_euler = (Vector(c["look_at"]) - ob.location).to_track_quat("-Z", "Y").to_euler()
+ ob["c3d_look_at"] = [float(v) for v in c["look_at"]] # the render driver's aim (Blender frame)
+ report["cameras"].append({"name": str(c["name"]), "object": ob.name})
+ first = first or ob
+ # the plan's camera order, by object name (the render driver reads it from the .blend)
+ bpy.context.scene["c3d_cameras"] = [c["object"] for c in report["cameras"]]
+ if first is not None:
+ bpy.context.scene.camera = first
+
+
+# ----------------------------------------------------------------------------- facts
+def _visible(inst: Any) -> bool:
+ host = inst.parent.original if inst.is_instance and inst.parent is not None else inst.object.original
+ return not host.hide_render
+
+
+def _tris(ob: Any) -> int:
+ if ob.type == "MESH":
+ ob.data.calc_loop_triangles()
+ return len(ob.data.loop_triangles)
+ try:
+ me = ob.to_mesh()
+ except RuntimeError:
+ return 0
+ try:
+ me.calc_loop_triangles()
+ return len(me.loop_triangles)
+ finally:
+ ob.to_mesh_clear()
+
+
+def _volume_density(node: Any) -> float | None:
+ sock = node.inputs.get("Density") if node is not None else None
+ return float(sock.default_value) if sock is not None and not sock.is_linked else None
+
+
+def _material_density(mat: Any) -> float | None:
+ """The density of the volume shader a volume material outputs (``None`` when unreadable)."""
+ tree = getattr(mat, "node_tree", None) if mat is not None else None
+ out = next((n for n in tree.nodes if n.bl_idname == "ShaderNodeOutputMaterial"), None) if tree is not None else None
+ if out is None or not out.inputs["Volume"].is_linked:
+ return None
+ return _volume_density(out.inputs["Volume"].links[0].from_node)
+
+
+def _world_facts(world: Any) -> tuple[dict[str, Any] | None, str | None]:
+ """(world-volume fog | None, background kind | None) of the scene's world."""
+ tree = getattr(world, "node_tree", None) if world is not None else None
+ if tree is None:
+ return None, None
+ out = next((n for n in tree.nodes if n.bl_idname == "ShaderNodeOutputWorld" and n.is_active_output),
+ next((n for n in tree.nodes if n.bl_idname == "ShaderNodeOutputWorld"), None))
+ if out is None:
+ return None, None
+ fog = None
+ if out.inputs["Volume"].is_linked:
+ fog = {"type": "WorldVolume", "near": None, "far": None,
+ "density": _volume_density(out.inputs["Volume"].links[0].from_node)}
+ background = None
+ if out.inputs["Surface"].is_linked:
+ node = out.inputs["Surface"].links[0].from_node
+ colour = node.inputs.get("Color") if node is not None else None
+ if colour is not None and colour.is_linked:
+ src = colour.links[0].from_node
+ background = {"ShaderNodeTexSky": f"sky:{getattr(src, 'sky_type', '')}",
+ "ShaderNodeTexEnvironment": "environment_texture"}.get(src.bl_idname, f"node:{src.bl_idname}")
+ elif colour is not None:
+ r, g, b = (max(0.0, min(1.0, float(v))) for v in list(colour.default_value)[:3])
+ background = f"#{round(r * 255):02x}{round(g * 255):02x}{round(b * 255):02x}"
+ else:
+ background = f"node:{node.bl_idname}"
+ return fog, background
+
+
+def _drivers(bpy: Any) -> list[dict[str, Any]]:
+ """Drivers that will not evaluate here: a Python (non-simple) expression — silently 0 under
+ ``--factory-startup`` (DESIGN §1.1) — or one Blender reports invalid (D10)."""
+ out: list[dict[str, Any]] = []
+ blocks = [("object", bpy.data.objects), ("material", bpy.data.materials), ("node_group", bpy.data.node_groups),
+ ("world", bpy.data.worlds), ("shape_key", bpy.data.shape_keys), ("mesh", bpy.data.meshes),
+ ("light", bpy.data.lights), ("scene", bpy.data.scenes)]
+ for kind, coll in blocks:
+ for idb in coll:
+ holders = [idb, getattr(idb, "node_tree", None)]
+ for h in holders:
+ ad = getattr(h, "animation_data", None) if h is not None else None
+ for fc in (ad.drivers if ad is not None else ()):
+ d = fc.driver
+ python = d.type == "SCRIPTED" and not d.is_simple_expression
+ if python or not d.is_valid:
+ out.append({"id": f"{kind}:{idb.name}", "path": fc.data_path, "index": fc.array_index,
+ "expression": d.expression if d.type == "SCRIPTED" else d.type,
+ "python": python, "valid": bool(d.is_valid)})
+ return out[:50]
+
+
+def handler_counts(bpy: Any) -> dict[str, int]:
+ """``{handler list: length}`` — Blender's own add-ons register some at startup, so what the
+ scene added is what grew."""
+ return {name: len(getattr(bpy.app.handlers, name)) for name in dir(bpy.app.handlers)
+ if not name.startswith("_") and isinstance(getattr(bpy.app.handlers, name), list)}
+
+
+def scene_facts(bpy: Any, handlers_before: dict[str, int]) -> dict[str, Any]:
+ """What only Blender knows (DESIGN §4.2): the keys the JS census fills for three.js
+ (``fog`` / ``background`` / ``environment`` / lights) plus drivers, handlers and triangles."""
+ dg = bpy.context.evaluated_depsgraph_get()
+ light_types: dict[str, int] = {}
+ unique: dict[Any, int] = {}
+ instanced = 0
+ volumes: list[dict[str, Any]] = []
+ for inst in dg.object_instances:
+ ob = inst.object
+ if not _visible(inst):
+ continue
+ if ob.type == "LIGHT":
+ light_types[ob.data.type] = light_types.get(ob.data.type, 0) + 1
+ continue
+ if ob.type not in ("MESH", "CURVE", "SURFACE", "FONT", "META") or (inst.is_instance and ob.type != "MESH"):
+ continue
+ src = ob if inst.is_instance else ob.original
+ if is_volume_only(src):
+ if not inst.is_instance:
+ dens = [d for d in map(_material_density, (s.material for s in src.material_slots)) if d is not None]
+ volumes.append({"object": src.name, "density": max(dens) if dens else None,
+ "size_m": [round(float(v), 3) for v in ob.dimensions]})
+ continue
+ n = _tris(ob)
+ instanced += n
+ unique.setdefault(ob.data.as_pointer() if inst.is_instance else ("obj", ob.original.name), n)
+ fog, background = _world_facts(bpy.context.scene.world)
+ if fog is None and volumes:
+ big = max(volumes, key=lambda v: v["size_m"][0] * v["size_m"][1] * v["size_m"][2])
+ fog = {"type": "VolumeBox", "near": None, "far": None, "density": big["density"], "object": big["object"],
+ "size_m": big["size_m"]}
+ handlers = sorted(n for n, k in handler_counts(bpy).items() if k > handlers_before.get(n, 0))
+ return {
+ "lights": sum(light_types.values()),
+ "light_types": light_types,
+ "fog": fog,
+ "background": background,
+ "environment": bpy.context.scene.world is not None,
+ "volumes": volumes,
+ "drivers_invalid": _drivers(bpy),
+ "handlers": handlers,
+ "unique_tris": sum(unique.values()),
+ "instanced_tris": instanced,
+ "volume_materials": sorted(m.name for m in bpy.data.materials if is_volume_material(m))[:20],
+ }
+
+
+# ----------------------------------------------------------------------------- main
+def main() -> int:
+ args = parse_args(wrapper_argv())
+ import bpy # noqa: PLC0415 — only available inside Blender
+
+ out_dir = os.path.abspath(args.out)
+ os.makedirs(out_dir, exist_ok=True)
+ script = os.path.abspath(args.scene)
+ src = os.path.dirname(script)
+ ws = os.path.dirname(src)
+ t0 = time.monotonic()
+ report = new_report(args.rlimit_gb, errors=[], zones_ok=[], zones_failed={}, cameras=[])
+ names = (REPORT_NAME, FACTS_NAME)
+ if not os.path.isfile(script):
+ report.update(error_type="FileNotFoundError", error_message=f"script not found: {script}")
+ write_report(out_dir, report, {}, t0, names=names)
+ return 0
+ first, last = (int(v) for v in args.frames.split(","))
+ prepare_scene(bpy, args.fps, (first, last))
+ seed_everything(args.seed)
+ render_before = render_fingerprint(bpy)
+ handlers_before = handler_counts(bpy)
+ purge_workspace_modules()
+
+ t_exec = time.monotonic()
+ exc, g = run_script(script) # src/ goes first on sys.path: `import env`, `zones.<snake>` resolve there
+ if exc is not None:
+ report.update(map_exception(exc, script, memory=MEMORY_HINT))
+ report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)
+ write_report(out_dir, report, {}, t0, names=names)
+ return 0
+ g = g or {}
+ zones: dict[str, str] = dict(g.get("ZONES") or {})
+ if args.zones is not None:
+ zones = {str(k): str(v) for k, v in json.loads(args.zones).items()}
+ ctx = SceneContext(bpy.context.scene, args.fps, tuple(float(t) for t in g.get("TIMES", (0.0, 1.5))))
+ stages = Stages(bpy, script, report)
+ build_env(bpy, ctx, stages, src)
+ assets_root = build_assets(bpy, ctx, stages, ws, dict(g.get("HEROES") or {}), dict(g.get("ASSETS") or {}), report)
+ if callable(g.get("create_scene")): # single-file mode: one scene.py builds everything
+ activate(bpy, bpy.context.scene.collection)
+ ctx.collection = bpy.context.scene.collection
+ stages.run("scene", "create_scene", "src/scene.py", lambda: g["create_scene"](ctx))
+ built = build_zones(bpy, ctx, stages, zones, report)
+ report["zones_ok"] = sorted(built)
+ report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)
+ with contextlib.suppress(RuntimeError):
+ if bpy.context.object and bpy.context.object.mode != "OBJECT":
+ bpy.ops.object.mode_set(mode="OBJECT")
+ lc = layer_collection(bpy.context.view_layer, assets_root)
+ if lc is not None:
+ lc.exclude = True # sources at the origin render only through their instances
+ add_cameras(bpy, list(g.get("CAMERAS") or []), report)
+ if render_fingerprint(bpy) != render_before:
+ report["warnings"].append("the scene changed render settings (engine/resolution/filepath/frames): "
+ "the harness owns them; delete that code")
+ bpy.context.scene.frame_set(first) # the census is the t = 0 pose
+
+ facts = scene_facts(bpy, handlers_before)
+ basis = [[float(v) for v in args.basis.split(",")[i * 3:i * 3 + 3]] for i in range(3)]
+ try:
+ facts["glb"] = write_census_glb(bpy, os.path.join(out_dir, GLB_NAME), basis=basis,
+ zones={name: name for name in built.values()}, cameras=list(g.get("CAMERAS") or []))
+ report["exported"]["glb"] = os.path.join(out_dir, GLB_NAME)
+ except Exception as e: # noqa: BLE001 — a writer failure is the harness's, reported as such
+ import traceback # noqa: PLC0415
+
+ report.update(error_type="CensusGlbError", error_message=f"census GLB writer failed: {e}",
+ traceback=traceback.format_exc()[-4000:])
+ if not args.no_blend:
+ blend = os.path.join(out_dir, BLEND_NAME)
+ try:
+ bpy.ops.wm.save_as_mainfile(filepath=blend, compress=True, copy=True)
+ report["exported"]["blend"] = blend
+ except Exception as e: # noqa: BLE001
+ report["warnings"].append(f".blend save failed: {e}")
+ report["ok"] = not report["error_type"] and "glb" in report["exported"]
+ write_report(out_dir, report, facts, t0, names=names)
+ return 0
+
+
+if __name__ == "__main__":
+ exit_after(main)
diff --git a/harness/codeverse3d/spatial/probes.py b/harness/codeverse3d/spatial/probes.py
index 9253dd34..436ca972 100644
--- a/harness/codeverse3d/spatial/probes.py
+++ b/harness/codeverse3d/spatial/probes.py
@@ -6,11 +6,19 @@
* ``probe_scene(ws)`` → (GateReport 'scene_probe', census) — the standalone probe
(the ``scene_probe`` tool, ``check_placement(rebuild=true)``)
* ``probe_report`` / ``shader_report`` — the two gates, pure over the driver JSON.
+
+An OFFLINE scene (scene_blender, D2/D3) is probed on its census GLB (``glb=``): the same driver,
+census and placement code through the harness adapter ``runtime_js/lib/glb_scene.mjs``, with no
+settle and no camera repair (the picture is Blender's, so the JS copy is never mutated), the bpy
+facts the GLB cannot carry merged into the census before any finding is drawn (``facts=``), and
+the triangle gate on UNIQUE triangles instead of the draw budget (D99 has no meaning offline).
"""
from __future__ import annotations
import time
+from collections.abc import Mapping
+from pathlib import Path
from typing import Any
from pydantic import BaseModel, Field
@@ -52,7 +60,7 @@ class SceneProbeResult(BaseModel):
yield self.census
-def _result(gate: GateReport, census: dict[str, Any]) -> SceneProbeResult:
+def probe_result(gate: GateReport, census: dict[str, Any]) -> SceneProbeResult:
"""A ``harness_failure`` finding IS a driver failure, wherever it was raised.
``ok`` is "the tool could run" (``registry.Observation.failed = not ok``) and the
@@ -70,22 +78,28 @@ def _f(gate: str, sev: Severity, msg: str, *, target: str | None = None, hint: s
def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None = None,
+ glb: Path | None = None, facts: Mapping[str, Any] | None = None,
) -> tuple[GateReport, GateReport, dict[str, Any]]:
"""One ``probe_scene.mjs`` boot → (scene_probe, shader_preflight, census).
``compile`` also runs the shader preflight on the same page; without it — or when the
scene never boots — the preflight is a failed-empty gate. ``timeout_s`` defaults to
the build timeout, capped at 120 s. A driver that cannot run is a ``harness_failure``
- finding, never a raise."""
+ finding, never a raise. ``glb`` probes an offline scene's census GLB instead of
+ ``src/scene.js`` (module docstring), ``facts`` its bpy census."""
t0 = time.time()
timeout_s = min(float(timeout_s or get_settings().limits.build_timeout_s), 120.0)
args = ["--ws", str(ws.root), "--out", str(ws.artifacts / "scene_probe.json"), "--timeout-ms", str(int(timeout_s * 1000))]
if compile:
args += ["--compile", "--shaders-out", str(ws.artifacts / "shader_preflight.json")]
- # every probe runs under the SAME settle / camera-repair / auto-exposure policy every
- # render uses — ONE parser, render_scene (review-3 S4: the build used to carry none of
- # the flags, so its gate measured a census the renders then contradicted)
- args += probe_env_args()
+ if glb is not None:
+ # D3: nothing moves the JS copy of a scene Blender renders — no settle, no camera repair
+ args += ["--glb", str(glb), "--no-settle"]
+ else:
+ # every probe runs under the SAME settle / camera-repair / auto-exposure policy every
+ # render uses — ONE parser, render_scene (review-3 S4: the build used to carry none of
+ # the flags, so its gate measured a census the renders then contradicted)
+ args += probe_env_args()
no_preflight = GateReport(gate=SHADER_GATE, passed=False, findings=[])
try:
res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)
@@ -93,6 +107,9 @@ def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None =
finding = _f(PROBE_GATE, Severity.ERROR, f"scene probe could not run: {e}"[:1500], target="src/scene.js",
hint="this is a harness/driver failure, not your code; retry or report", harness_failure=True)
return GateReport.of(PROBE_GATE, [finding], duration_ms=int((time.time() - t0) * 1000)), no_preflight, {}
+ if glb is not None:
+ probe, census = offline_report(res.summary, facts or {}, duration_ms=int((time.time() - t0) * 1000))
+ return probe, no_preflight, census
probe, census = probe_report(res.summary, duration_ms=int((time.time() - t0) * 1000))
rep = res.summary.get("shader_report") or {}
if not compile or not rep or rep.get("skipped"):
@@ -105,7 +122,7 @@ def probe_scene(ws: Workspace, *, timeout_s: float = 60.0) -> SceneProbeResult:
report, _, census = run_probe(ws, timeout_s=timeout_s)
if census:
ws.write_json(ws.artifacts / "census.json", census)
- return _result(report, census)
+ return probe_result(report, census)
def probe_report(summary: dict[str, Any], *, duration_ms: int = 0) -> tuple[GateReport, dict[str, Any]]:
@@ -170,7 +187,71 @@ def probe_report(summary: dict[str, Any], *, duration_ms: int = 0) -> tuple[Gate
return GateReport.of(gate, findings, duration_ms=duration_ms), census
-def _census_findings(c: dict[str, Any]) -> list[GateFinding]:
+#: census keys an offline scene's bpy facts own: the JS census of a GLB cannot see a world, a
+#: volume or a lamp, so its own values for these are replaced, never mixed
+FACT_KEYS = ("fog", "background", "environment", "light_types")
+
+
+def merge_facts(census: dict[str, Any], facts: Mapping[str, Any]) -> dict[str, Any]:
+ """The GLB census with the bpy facts in the keys the gates already read (``fog``,
+ ``background``, ``totals.lights`` …) and the rest under ``bpy``."""
+ if not census:
+ return {}
+ out = {**census, **{k: facts[k] for k in FACT_KEYS if k in facts}}
+ out["totals"] = {**(census.get("totals") or {}), "lights": int(facts.get("lights") or 0)}
+ out["bpy"] = {k: v for k, v in facts.items() if k not in FACT_KEYS and k != "lights"}
+ return out
+
+
+def offline_report(summary: dict[str, Any], facts: Mapping[str, Any], *, duration_ms: int = 0) -> tuple[GateReport, dict[str, Any]]:
+ """The ``scene_probe`` gate of an offline scene over its census-GLB probe. The host loaded a
+ file the HARNESS wrote, so a boot or console failure is the harness's (``harness_failure``),
+ never the agent's; the verdict is the census's."""
+ boot = summary.get("boot") or {}
+ fail = [e for e in summary.get("console_errors", []) if not e.startswith("boot[")]
+ if not boot.get("ok"):
+ fail.insert(0, f"[{boot.get('stage', '?')}] {boot.get('error') or 'no probe result (driver output lost)'}")
+ if fail:
+ finding = _f(PROBE_GATE, Severity.ERROR, f"the census GLB did not load cleanly in the probe host: {fail[0]}"[:1500],
+ target="artifacts/census.glb", hint="this is a harness failure, not your code; retry or report",
+ harness_failure=True)
+ return GateReport.of(PROBE_GATE, [finding], duration_ms=duration_ms), {}
+ findings = [_f(PROBE_GATE, Severity(p["severity"]), f"cameras: {p['text']}", target="src/scene.py",
+ hint="the plan's cameras become src/scene.py CAMERAS at assembly")
+ for p in boot.get("camera_problems", [])]
+ census = merge_facts(summary.get("census") or {}, facts)
+ findings.extend(_census_findings(census, offline=True))
+ return GateReport.of(PROBE_GATE, findings, duration_ms=duration_ms), census
+
+
+def _offline_findings(c: dict[str, Any]) -> list[GateFinding]:
+ """What only an offline scene can get wrong: a triangle count the renderer must hold in
+ memory (UNIQUE triangles — an instance costs a matrix, not a mesh; D2), drivers the build
+ will never evaluate (D10) and frame handlers the deliverable would depend on."""
+ bpy = c.get("bpy") or {}
+ out: list[GateFinding] = []
+ unique = int(bpy.get("unique_tris") or 0)
+ if unique > MAX_TRIS_SCENE:
+ out.append(_f(PROBE_GATE, Severity.ERROR,
+ f"{unique:,} unique triangles (instanced copies not counted) exceed the {MAX_TRIS_SCENE:,} budget",
+ target="scene", kind="unique_tris", unique_tris=unique, limit=MAX_TRIS_SCENE,
+ hint="place repeats as collection instances or geometry-nodes instances instead of copies, and lower "
+ "subdivision levels / segment counts on large meshes"))
+ for d in (bpy.get("drivers_invalid") or [])[:8]:
+ why = "runs Python, which the harness never executes (it evaluates to 0)" if d.get("python") else "is invalid"
+ out.append(_f(PROBE_GATE, Severity.ERROR,
+ f"driver {d.get('id')} {d.get('path')}[{d.get('index')}] = {str(d.get('expression'))[:120]!r} {why}",
+ target=str(d.get("id") or "scene"), kind="python_driver",
+ hint="use keyframes, or a simple expression of `frame` (sin/cos/min/max/clamp/lerp, + - * / and "
+ "comparisons, no attribute access, no ** or %)"))
+ for h in bpy.get("handlers") or []:
+ out.append(_f(PROBE_GATE, Severity.ERROR, f"bpy.app.handlers.{h} is set: the deliverable .blend would depend on "
+ "code that does not travel with it", target="scene", kind="app_handler",
+ hint="animate with keyframes, simple drivers or the geometry-nodes Scene Time node"))
+ return out
+
+
+def _census_findings(c: dict[str, Any], *, offline: bool = False) -> list[GateFinding]:
gate = PROBE_GATE
out: list[GateFinding] = []
if not c:
@@ -187,15 +268,24 @@ def _census_findings(c: dict[str, Any]) -> list[GateFinding]:
kind="unobserved_animation_hook", hook_path=hook.get("path"),
))
tot = c.get("totals", {})
- if tot.get("lights", 0) == 0:
- out.append(_f(gate, Severity.WARN, "scene has no lights (MeshStandardMaterial renders black)", target="src/env.js",
- hint="add new THREE.DirectionalLight (castShadow) + new THREE.HemisphereLight in buildEnv"))
- if tot.get("meshes", 0) == 0:
- out.append(_f(gate, Severity.ERROR, "scene has no meshes", target="src/scene.js", hint="add zones to the scene in createScene"))
- 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))
+ if offline:
+ if tot.get("lights", 0) == 0 and not c.get("background"):
+ out.append(_f(gate, Severity.WARN, "scene has no lamps and no world: it renders black", target="src/env.py",
+ hint="in build_env create a world (Sky Texture) and a Sun lamp"))
+ if tot.get("meshes", 0) == 0:
+ out.append(_f(gate, Severity.ERROR, "scene has no meshes", target="src/scene.py",
+ hint="every zone's build(ctx) links its objects into ctx.collection"))
+ out.extend(_offline_findings(c))
+ else:
+ if tot.get("lights", 0) == 0:
+ out.append(_f(gate, Severity.WARN, "scene has no lights (MeshStandardMaterial renders black)", target="src/env.js",
+ hint="add new THREE.DirectionalLight (castShadow) + new THREE.HemisphereLight in buildEnv"))
+ if tot.get("meshes", 0) == 0:
+ out.append(_f(gate, Severity.ERROR, "scene has no meshes", target="src/scene.js", hint="add zones to the scene in createScene"))
+ 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",
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 237ed64f..72b0e6b8 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -121,13 +121,14 @@ codeverse3d/
provider_wait), materialize.py
languages/ LanguageRuntime + RuntimeLayout (base.py: every runtime states its file layout —
expected_files / files_for — and the tracks ask it); one merged module per language since 2026-08-28 —
- blender/ cadquery/ threejs/ urdf/ scene_threejs/ glsl_shader/ opengl_python/ are each
+ blender/ cadquery/ threejs/ urdf/ scene_threejs/ scene_blender/ glsl_shader/ opengl_python/ are each
a single __init__.py (lint → skeleton → runtime, in dependency order) beside their
data (starter/, opengl_python/wrappers/run_gl.py; the contract text is
prompts/<lang>/contract.md, found like every per-language prompt file by
prompts/catalog.language_prompt — a runtime holds no prompt text); wrappers/
- holds the python build wrappers (run_bpy, run_bpy_links, run_cq) and what they
- share (_wrapper_common: script run + error mapping + report; _census: the Blender census)
+ holds the python build wrappers (run_bpy, run_bpy_links, run_cq, run_bpy_scene) and what they
+ share (_wrapper_common: script run + error mapping + report; _census: the Blender census;
+ _census_glb: scene_blender's census GLB writer, D102)
spatial/ node.py, render.py, observe.py, tool_common.py (shared tool plumbing),
render_scene.py (judge view subset, content-fitted orbit),
frame_metrics.py (scene_frames gate), frame_motion.py (measured inter-frame motion),
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index a9094bf8..ee76ee4f 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -257,6 +257,10 @@ rt.asset_file(asset: AssetPlan) -> str # factory module, or publ
rt.assemble(ws, plan: ScenePlan) -> BaseModel # writes the entry; plan cameras, else derived; artifacts/assemble.json
rt.probe(ws, *, timeout_s=60.0) -> SceneProbeResult # scene_probe gate + census.json (scene_probe / check_placement tools)
rt.render_scene(ws, out_dir, *, cameras=None, orbit=True, times=(0.0, 1.5), width=1024, height=576, sheet=True) -> RenderSet
+# Δ 2026-09-24 (D102) spatial.probes.run_probe(ws, *, compile=False, timeout_s=None, glb: Path | None = None, facts=None):
+# glb = an OFFLINE scene's census GLB (probe_scene.mjs --glb → runtime_js/lib/glb_scene.mjs, served at /__census.glb;
+# host_page.openHost(..., glb=)), facts merged into the census by probes.merge_facts before any finding;
+# probes.probe_result (was _result); conventions.glb_basis(language) (3×3, language frame → GLB frame)
from codeverse3d.prompts.catalog import language_prompt, language_text
language_prompt(language, name) -> str # "<dir>/<name>" under prompts/ (urdf_blender → urdf/): THE per-language prompt
language_text(language, name) -> str # its text, "" for a file the language does not ship (Δ 2026-09-22: replaces
@@ -272,6 +276,7 @@ BuildResult.error_type spellings (languages/_common.py): MISSING_ENTRY = "Missin
| `ThreeJsRuntime` | `src/object.js`, `src/parts/*.js` | **Δ export as authored** (census `placement_offset`); InstancedMesh baked to `<Name>_<i>` meshes (`instanced_meshes_baked`); exported `selfcheck(THREE, root)` is called (throw → SelfCheckError); NaN geometry errors name mesh/part → routed to `src/parts/<snake>.js` |
| `UrdfBlenderRuntime` | `src/model.py`, `src/robot.urdf` | object.glb (Y-up, node=link, joint extras), meshes/<link>.glb (raw Z-up link frames); link name `world` is reserved (lint ERROR + UrdfError); robot GLB root gets `__root` suffix on name clash; the build collides the REST pose only (RestPenetration > 5 mm, D17) — every pose is the round's `joint_sweep` gate — and writes no articulation.json / census.articulation (Δ 2026-09-22) |
| `SceneThreeJsRuntime` | `src/scene.js`, `src/zones/*.js`, `src/assets/*.js`, `src/env.js`, `src/shaders/*.{js,vert,frag,glsl}` | glb_path=None; local shader text loads inside async createScene; ok iff `spatial.probes.run_probe(ws, *, compile=True, timeout_s=None) -> (scene_probe, shader_preflight, census)` (one `probe_scene.mjs --compile` boot; `probe_scene` is the same call without `compile`) passes both; both reports ride `BuildResult.gates`, and the `shader_probe` tool reports the same call |
+| `SceneBlenderRuntime` | `src/scene.py`, `src/zones/*.py`, `src/assets/*.py`, `src/env.py` | **Δ 2026-09-24 (D102)** glb_path=None; `scene.py` is assembled DATA (`ZONES`/`ASSETS`/`HEROES` `{snake: Pascal}`, `CAMERAS` in the Blender frame, vertical fov); build = one Blender process (`wrappers/run_bpy_scene.py`: env, heroes, assets, zones each isolated — a raise is an ERROR on its `file:line` and the zone is dropped) → `artifacts/{census.glb, scene.blend, bpy_build.json, bpy_census.json}` → `run_probe(ws, glb=artifacts/census.glb, facts=bpy_census)` (no settle / camera repair; D2 unique-tri ERROR, no draw gate; D10 python drivers ERROR) → `BuildResult.gates=[scene_probe]`; `probe()` = the same measurement without touching build.json; `render_scene` raises NotImplementedError until DESIGN phase 2; frame clock `scene_blender.FPS`/`frame_of(t) = 1 + round(30 t)` |
| `GlslShaderRuntime` | `src/shader.frag`, `src/common.glsl`, `src/buffer_a.frag` (+ the harness-owned `src/recipes.glsl` when seeded) | harness owns `#version`/uniforms/`out` (wrap.HEADER: u_time/u_resolution/u_mouse/u_frame/u_prev/u_noise + iTime/iChannel* aliases); `wrap.compose(shader, common, recipes_src=…)` pastes header < recipes < common < shader; build renders judge frames via GlHost; compile errors → GlslCompileError at mapped src file:line (recipes.glsl included); lint ERROR `redefines_recipe` when an agent file defines a recipes.glsl name; artifacts frames/, frames_sheet.png, preview.gif, metrics.json |
| `OpenGLPythonRuntime` | `src/program.py`, `src/*.glsl` | `setup(ctx,w,h)->state` + `render(ctx,state,t,frame,fbo)` run in a moderngl subprocess (`wrappers/run_gl.py`); exceptions map to src/program.py:line, in-string GLSL errors carry both line numbers |
@@ -284,7 +289,7 @@ cannot opt in (`runtime_js/lib/backdrop.mjs`).
Wrappers are standalone (never import codeverse3d). The three python build wrappers live
together in `languages/wrappers/` — `run_bpy.py`, `run_bpy_links.py` (Blender's python 3.11),
-`run_cq.py` — beside the sibling modules they import from their own directory:
+`run_cq.py`, and `run_bpy_scene.py` + `_census_glb.py` (scene_blender, D102) — beside the sibling modules they import from their own directory:
`_wrapper_common.py` (stdlib only: rlimit, seeding, running the script with `src/` on
`sys.path`, traceback → `src/<file>:<line>`, `sys.exit(0)` is not a failure, the atomic
report) and `_census.py` (the Blender census, blender AND urdf_blender); copy the directory
diff --git a/harness/runtime_js/lib/glb_scene.mjs b/harness/runtime_js/lib/glb_scene.mjs
new file mode 100644
index 00000000..53f1c29c
--- /dev/null
+++ b/harness/runtime_js/lib/glb_scene.mjs
@@ -0,0 +1,22 @@
+/**
+ * The scene module of an OFFLINE scene (scene_blender, DESIGN §4.2): the `createScene` the host
+ * imports when a driver is given `--glb`. The harness-written census GLB (languages/wrappers/
+ * _census_glb.py) is served at CENSUS_GLB_URL; its root nodes are hoisted into the scene — env
+ * objects by name, one group per zone — and the harness cameras come from the scene's
+ * `extras.c3d_cameras` (GLB frame). The GLB is the t = 0 pose, so `update` changes nothing:
+ * motion is measured on the Blender frames. Nothing here is the agent's code.
+ */
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+
+export const CENSUS_GLB_URL = '/__census.glb';
+
+export async function createScene() {
+ const scene = new THREE.Scene();
+ // its own loader, not the host's: the host's records every GLB a scene loads as a hero
+ // (census `glb_assets`), and the census GLB is the whole scene, not a hero
+ const gltf = await new GLTFLoader().loadAsync(CENSUS_GLB_URL);
+ for (const child of [...gltf.scene.children]) scene.add(child);
+ const cameras = (gltf.scene.userData && gltf.scene.userData.c3d_cameras) || [];
+ return { scene, cameras, update() {} };
+}
diff --git a/harness/runtime_js/lib/host_env.mjs b/harness/runtime_js/lib/host_env.mjs
index 74ac5d28..08eab397 100644
--- a/harness/runtime_js/lib/host_env.mjs
+++ b/harness/runtime_js/lib/host_env.mjs
@@ -6,6 +6,7 @@
* `render_glb.mjs` (objects) — no other module reaches for the CJS files.
*/
+import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
@@ -29,9 +30,10 @@ export const { serveDirs, importMapHtml, RUNTIME_MOUNT } = serve;
* /assets/** → <ws>/public/assets (contract: '/assets/x.glb')
* <RUNTIME_MOUNT>/** → runtime_js (node_modules/three, lib/*.mjs)
* /__host.html → generated host page (import map + scene_host.mjs)
+ * /__census.glb → `glb` (an offline scene's census GLB, lib/glb_scene.mjs), when given
* @returns {Promise<{server, base: string, close: () => Promise<void>}>}
*/
-export async function serveWorkspace(wsRoot, { hostHtml = '' } = {}) {
+export async function serveWorkspace(wsRoot, { hostHtml = '', glb = null } = {}) {
wsRoot = path.resolve(wsRoot);
const srv = await serve.serveDirs({
// explicit mounts, no `root`: the workspace root also holds spec.json, run_state.json,
@@ -41,7 +43,11 @@ export async function serveWorkspace(wsRoot, { hostHtml = '' } = {}) {
'/public/': path.join(wsRoot, 'public'),
'/assets/': path.join(wsRoot, 'public', 'assets'),
},
- routes: { '/__host.html': { body: hostHtml, type: 'text/html; charset=utf-8' } },
+ routes: {
+ '/__host.html': { body: hostHtml, type: 'text/html; charset=utf-8' },
+ // one file by exact path: artifacts/ itself stays unserved
+ ...(glb ? { '/__census.glb': { body: fs.readFileSync(glb), type: 'model/gltf-binary' } } : {}),
+ },
});
return { server: srv.server, base: srv.base, close: srv.close };
}
diff --git a/harness/runtime_js/lib/host_page.mjs b/harness/runtime_js/lib/host_page.mjs
index 34d7ed53..c1a45345 100644
--- a/harness/runtime_js/lib/host_page.mjs
+++ b/harness/runtime_js/lib/host_page.mjs
@@ -52,12 +52,15 @@ export function requestFailureLine(url, base, hasResponse, errorText) {
* Open the host for workspace `wsRoot`.
* @returns {Promise<{page, browser, base, gpu, renderer, errors, boot, close}>}
*/
-export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true, cameraRepair = false, autoExposure = false, post = true, postOptions = null } = {}) {
+export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true, cameraRepair = false, autoExposure = false, post = true, postOptions = null, glb = null } = {}) {
wsRoot = path.resolve(wsRoot);
- if (!fs.existsSync(path.join(wsRoot, sceneRel))) {
- throw new Error(`missing ${sceneRel} in workspace ${wsRoot}`);
+ // an offline scene (`glb`: its census GLB) boots the harness adapter, never a workspace module
+ const sceneFile = glb || path.join(wsRoot, sceneRel);
+ if (!fs.existsSync(sceneFile)) {
+ throw new Error(glb ? `missing census GLB ${glb}` : `missing ${sceneRel} in workspace ${wsRoot}`);
}
- const srv = await serveWorkspace(wsRoot, { hostHtml: hostHtml() });
+ const sceneUrl = glb ? `${RUNTIME_MOUNT}lib/glb_scene.mjs` : `/${sceneRel}`;
+ const srv = await serveWorkspace(wsRoot, { hostHtml: hostHtml(), glb });
const errors = { console: [], page: [], shader_console: [], warnings: [] };
let launched = null;
let page = null;
@@ -98,7 +101,7 @@ export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto
await page.waitForFunction('window.__c3v_ready === true', { timeout: 60000 });
const boot = await page.evaluate(
(o) => window.__c3v.boot(o),
- { sceneUrl: `/${sceneRel}`, width, height, logDepth, createSceneTimeoutMs, settle, cameraRepair, autoExposure, post, postOptions },
+ { sceneUrl, width, height, logDepth, createSceneTimeoutMs, settle, cameraRepair, autoExposure, post, postOptions },
);
const close = async () => {
// page first, then release: a SHARED browser (connect-first reuse) must get
diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjs
index f3e98e13..27c6ad93 100644
--- a/harness/runtime_js/probe_scene.mjs
+++ b/harness/runtime_js/probe_scene.mjs
@@ -7,6 +7,10 @@
*
* node probe_scene.mjs --ws <ws> [--scene src/scene.js] [--gpu auto] [--timeout-ms 60000] [--out probe.json]
* [--compile] [--shaders-out report.json] [--sun-azimuth 60] [--bounds '{"min":[..],"max":[..]}'|none]
+ * [--glb artifacts/census.glb]
+ *
+ * `--glb` probes an OFFLINE scene (scene_blender): the host boots lib/glb_scene.mjs on that
+ * harness-written census GLB instead of `--scene` — the same census and placement code.
*
* `--compile` additionally runs the full shader preflight (static GLSL audits +
* force-compile of every material, lib/shader_report.mjs) on the SAME booted
@@ -39,7 +43,7 @@ const args = parseCli({
// flag parses (drivers share a switch list) and changes nothing.
'no-post': { type: 'boolean', default: false },
ws: {}, out: {}, gpu: { default: process.env.C3D_RENDER_GPU || 'auto' }, 'timeout-ms': { default: '60000' },
- scene: { default: 'src/scene.js' },
+ scene: { default: 'src/scene.js' }, glb: { default: '' },
compile: { type: 'boolean', default: false }, 'shaders-out': { default: '' }, 'sun-azimuth': { default: '' },
bounds: { default: 'none' },
});
@@ -70,6 +74,7 @@ async function main() {
try {
host = await openHost(args.ws, {
width: 320, height: 180, gpu: args.gpu, sceneRel: args.scene.replace(/^\.?\//, ''),
+ glb: args.glb ? path.resolve(args.glb) : null,
createSceneTimeoutMs: createTimeoutMs(timeoutMs),
settle: !args['no-settle'],
cameraRepair: !!args['camera-repair'],
diff --git a/harness/tests/prompts/manifest.py b/harness/tests/prompts/manifest.py
index 6928d581..d2dbdb03 100644
--- a/harness/tests/prompts/manifest.py
+++ b/harness/tests/prompts/manifest.py
@@ -453,11 +453,16 @@ def run_scenario(name: str, root: Path) -> Result:
return Result(capture(rig), stage_keys(rig))
+#: a language whose agent-facing payloads are not blessed yet: scene_blender's tool list is blessed by
+#: the lane that ships its prompts and scenarios (DESIGN phase 3), which deletes this entry
+UNBLESSED_LANGUAGES = frozenset({Language.SCENE_BLENDER})
+
+
def mcp_tools() -> dict[str, str]:
"""The tool list an MCP session is offered, per (track, language)."""
return {f"mcp_tools:{t.value}/{lang.value}": _json([{"name": d.name, "cost": d.cost_hint, "description": d.description,
"schema": d.schema()} for d in list_tools(track=t.value, language=lang.value)])
- for t, langs in TRACK_LANGUAGES.items() for lang in langs}
+ for t, langs in TRACK_LANGUAGES.items() for lang in langs if lang not in UNBLESSED_LANGUAGES}
def capture(rig: Rig) -> dict[str, str]:
diff --git a/harness/tests/prompts/test_files.py b/harness/tests/prompts/test_files.py
index f5ffdc63..96d105a6 100644
--- a/harness/tests/prompts/test_files.py
+++ b/harness/tests/prompts/test_files.py
@@ -23,11 +23,16 @@ def test_prompt_file_contract(rel: str) -> None:
assert seq not in raw, f"{rel} contains {seq!r} which breaks jinja rendering"
+#: languages whose prompt files have not landed yet — scene_blender's are DESIGN phase 3 (lane C),
+#: which deletes this entry when prompts/scene_blender/ ships
+PROMPTS_PENDING = frozenset({Language.SCENE_BLENDER})
+
+
def test_every_language_ships_a_system_prompt_a_contract_and_a_cookbook() -> None:
"""A missing per-language file silently reads as "" through ``language_text``."""
from codeverse3d.tracks.prompting import language_system_prompt
- for lang in Language:
+ for lang in (lang for lang in Language if lang not in PROMPTS_PENDING):
text = language_system_prompt(lang)
assert text.strip(), f"{lang.value}: empty system prompt"
for name in ("system.md", "contract.md", "cookbook.md"):
diff --git a/harness/tests/scene_blender/__init__.py b/harness/tests/scene_blender/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/scene_blender/fixtures.py b/harness/tests/scene_blender/fixtures.py
new file mode 100644
index 00000000..25606fb0
--- /dev/null
+++ b/harness/tests/scene_blender/fixtures.py
@@ -0,0 +1,143 @@
+"""A hand-written scene_blender workspace with one of everything the census GLB must carry.
+
+Blender frame (Z up, -Y front). ``yard`` places four crates as collection instances — seated,
+floating 1.5 m, sunk 0.6 m, and one tagged ``placement = 'free'`` — plus a parented cart (a mesh
+with a child mesh: one placement row). ``meadow`` scatters grass blades with geometry nodes (an
+instance cloud). ``broken`` raises on a known line. ``CRATE_TRIS`` etc. are what bpy must count.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse3d.workspace import Workspace
+
+SCENE = '''ZONES = {"yard": "Yard", "meadow": "Meadow", "broken": "Broken"}
+ASSETS = {"crate": "Crate"}
+HEROES = {}
+CAMERAS = [{"name": "overview", "location": (30.0, -30.0, 18.0), "look_at": (0.0, 0.0, 0.0), "fov": 50}]
+'''
+
+ENV = '''import bmesh
+import bpy
+
+
+def height_at(x, y):
+ return 0.0
+
+
+def build_env(ctx):
+ world = bpy.data.worlds.new("Sky")
+ ctx.scene.world = world
+ me = bpy.data.meshes.new("Ground")
+ bm = bmesh.new()
+ bmesh.ops.create_grid(bm, x_segments=10, y_segments=10, size=40)
+ bm.to_mesh(me)
+ bm.free()
+ ctx.collection.objects.link(bpy.data.objects.new("Ground", me))
+ ctx.collection.objects.link(bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN")))
+ return {}
+'''
+
+CRATE = '''import bmesh
+import bpy
+
+
+def build_crate(ctx, variant=0):
+ me = bpy.data.meshes.new("CrateBody")
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.translate(bm, vec=(0, 0, 0.5), verts=bm.verts)
+ bm.to_mesh(me)
+ bm.free()
+ ctx.collection.objects.link(bpy.data.objects.new("CrateBody", me))
+ return ctx.collection
+'''
+
+YARD = '''import bpy
+
+
+def place(ctx, name, x, y, z):
+ e = bpy.data.objects.new(name, None)
+ e.instance_type = "COLLECTION"
+ e.instance_collection = ctx.assets["crate"]
+ e.location = (x, y, z)
+ ctx.collection.objects.link(e)
+ return e
+
+
+def build(ctx):
+ place(ctx, "Crate_0", 0.0, 0.0, 0.0)
+ place(ctx, "Crate_1", 4.0, 0.0, 1.5)
+ place(ctx, "Crate_2", -4.0, 0.0, -0.6)
+ bird = place(ctx, "Crate_3", 0.0, 5.0, 3.0)
+ bird["placement"] = "free"
+ bpy.ops.mesh.primitive_cube_add(size=1, location=(8, 0, 0.5))
+ cart = bpy.context.object
+ cart.name = "Cart_0"
+ bpy.ops.mesh.primitive_cylinder_add(radius=0.3, depth=0.2, location=(8, 0.6, 0.3))
+ wheel = bpy.context.object
+ wheel.name = "CartWheel_0"
+ wheel.parent = cart
+ wheel.matrix_parent_inverse = cart.matrix_world.inverted()
+ return ctx.collection
+'''
+
+MEADOW = '''import bpy
+
+
+def build(ctx):
+ bpy.ops.mesh.primitive_plane_add(size=10, location=(0, -12, 0))
+ patch = bpy.context.object
+ patch.name = "GrassPatch"
+ bpy.ops.mesh.primitive_cone_add(vertices=4, radius1=0.05, depth=0.3, location=(0, 0, -50))
+ blade = bpy.context.object
+ blade.name = "Blade"
+ blade.hide_render = True
+ blade.hide_viewport = True
+ ng = bpy.data.node_groups.new("Scatter", "GeometryNodeTree")
+ ng.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")
+ ng.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")
+ n = ng.nodes
+ gi, go = n.new("NodeGroupInput"), n.new("NodeGroupOutput")
+ dist = n.new("GeometryNodeDistributePointsOnFaces")
+ dist.inputs["Density"].default_value = 5.0
+ inst = n.new("GeometryNodeInstanceOnPoints")
+ info = n.new("GeometryNodeObjectInfo")
+ info.inputs["Object"].default_value = blade
+ join = n.new("GeometryNodeJoinGeometry")
+ ng.links.new(gi.outputs[0], dist.inputs["Mesh"])
+ ng.links.new(dist.outputs["Points"], inst.inputs["Points"])
+ ng.links.new(info.outputs["Geometry"], inst.inputs["Instance"])
+ ng.links.new(inst.outputs["Instances"], join.inputs["Geometry"])
+ ng.links.new(gi.outputs[0], join.inputs["Geometry"])
+ ng.links.new(join.outputs[0], go.inputs[0])
+ patch.modifiers.new("Scatter", "NODES").node_group = ng
+ return ctx.collection
+'''
+
+#: the line of ``broken.py`` that raises (after leaving a stray object in the scene root)
+BROKEN_LINE = 7
+BROKEN = '''import bpy
+
+
+def build(ctx):
+ bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 12, 0.5))
+ ctx.scene.collection.objects.link(bpy.data.objects.new("Stray", bpy.context.object.data))
+ missing = {}["no_such_key"]
+ return ctx.collection
+'''
+
+
+def write_fixture(ws: Workspace, *, broken: bool = True) -> Workspace:
+ files = {"src/scene.py": SCENE, "src/env.py": ENV, "src/assets/crate.py": CRATE, "src/zones/yard.py": YARD,
+ "src/zones/meadow.py": MEADOW}
+ if broken:
+ files["src/zones/broken.py"] = BROKEN
+ else:
+ files["src/scene.py"] = SCENE.replace(', "broken": "Broken"', "")
+ for rel, text in files.items():
+ p: Path = ws.root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text)
+ return ws
diff --git a/harness/tests/scene_blender/test_build.py b/harness/tests/scene_blender/test_build.py
new file mode 100644
index 00000000..798ae7d9
--- /dev/null
+++ b/harness/tests/scene_blender/test_build.py
@@ -0,0 +1,176 @@
+"""scene_blender build end to end: Blender builds the workspace, the harness writes the census GLB,
+the unchanged JS census / placement code measures it (real Blender + headless Chrome)."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.contracts.plan import ScenePlan
+from codeverse3d.conventions import to_snake
+from codeverse3d.languages import get_runtime
+from codeverse3d.languages.scene_blender import SceneBlenderRuntime
+from codeverse3d.tracks.planner import plan_example
+from tests.scene_blender.fixtures import BROKEN_LINE, write_fixture
+from tests.scene_runtime.conftest import needs_browser
+from tests.scene_runtime.glb_fixture import write_box_glb
+
+needs_blender = pytest.mark.skipif(not get_settings().resolve_blender(), reason="no Blender binary")
+pytestmark = [pytest.mark.blender, pytest.mark.node, needs_blender, needs_browser]
+
+
+def _rt() -> SceneBlenderRuntime:
+ return get_runtime(Language.SCENE_BLENDER) # type: ignore[return-value]
+
+
[email protected](scope="module")
+def built(tmp_path_factory):
+ """One build of the fixture (every case in one Blender process, one probe)."""
+ from codeverse3d.workspace import Workspace
+
+ ws = write_fixture(Workspace(tmp_path_factory.mktemp("sb") / "run").create())
+ return ws, _rt().build(ws)
+
+
+def _rows(res) -> dict[str, dict]:
+ return {r["name"]: r for r in res.census["placement"]["assets"]}
+
+
+def test_triangle_parity_bpy_vs_the_census_glb(built) -> None:
+ """Every evaluated triangle Blender renders reaches the JS census through the GLB — collection
+ instances as clones, the geometry-nodes grass as an instance cloud (the official exporter drops
+ those silently, DESIGN §1.4)."""
+ _, res = built
+ bpy, totals = res.census["bpy"], res.census["totals"]
+ assert bpy["instanced_tris"] == totals["triangles"] > 0
+ assert bpy["glb"]["clouds"] == 1 and bpy["glb"]["instances"] > 100
+ assert totals["instances"] >= bpy["glb"]["instances"]
+ assert bpy["unique_tris"] < bpy["instanced_tris"] # an instance costs a matrix, not a mesh
+
+
+def test_a_zone_that_raises_is_dropped_with_its_file_and_line(built) -> None:
+ ws, res = built
+ assert not res.ok
+ assert (res.error_file, res.error_line, res.error_type) == ("src/zones/broken.py", BROKEN_LINE, "zone_error")
+ groups = {g["name"] for g in res.census["groups"]}
+ assert {"Yard", "Meadow"} <= groups and "Broken" not in groups # the rest still built and was measured
+ report = json.loads((ws.artifacts / "bpy_build.json").read_text())
+ assert set(report["zones_failed"]) == {"broken"} and report["zones_ok"] == ["meadow", "yard"]
+ # what it made before raising is gone with it — even the object it linked outside its zone
+ assert not [r for r in res.census["placement"]["assets"] if r["name"].startswith(("Cube", "Stray"))]
+
+
+def test_placement_rows_for_sunk_floating_and_free(built) -> None:
+ _, res = built
+ rows = _rows(res)
+ assert rows["Crate_0"]["supported"] and not rows["Crate_0"]["floating"]
+ assert rows["Crate_1"]["floating"] and rows["Crate_1"]["ground_gap_m"] == pytest.approx(1.5, abs=0.02)
+ assert rows["Crate_2"]["sunk_m"] == pytest.approx(0.6, abs=0.02)
+ assert rows["Crate_3"]["exempt"] == "free" # obj["placement"] = "free" → glTF extras → userData
+ assert rows["Cart_0"]["zone"] == "Yard" # a parent mesh + child: ONE row
+ assert "CartWheel_0" not in rows
+ assert [r["name"] for r in rows.values() if r["name"].startswith("GrassPatch")] == ["GrassPatch"]
+
+
+def test_bpy_facts_reach_the_census(built) -> None:
+ ws, res = built
+ c = res.census
+ assert c["totals"]["lights"] == 1 and c["light_types"] == {"SUN": 1}
+ assert c["environment"] is True
+ assert c["bpy"]["drivers_invalid"] == [] and c["bpy"]["handlers"] == []
+ assert (ws.artifacts / "scene.blend").stat().st_size > 0 and (ws.artifacts / "census.glb").stat().st_size > 0
+ assert [g.gate for g in res.gates] == ["scene_probe"]
+
+
+def test_the_skeleton_builds_and_passes(tmp_ws) -> None:
+ """plan → skeleton → assemble → build: the starter scene passes its own gates, the fog volume
+ is a fact (not matter), the sky a background, the plan's cameras reach the host."""
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ rt = _rt()
+ rt.skeleton(tmp_ws, plan)
+ assert rt.lint(tmp_ws).passed
+ asm = rt.assemble(tmp_ws, plan)
+ assert set(asm.zones_included) == {"quay", "water"} and not asm.zones_failed
+ res = rt.build(tmp_ws)
+ assert res.ok, res.stdout_tail
+ c = res.census
+ assert c["fog"]["type"] == "VolumeBox" and c["background"] == "sky:MULTIPLE_SCATTERING"
+ assert "Atmosphere" in c["bpy"]["glb"]["volumes_skipped"]
+ assert {g["name"] for g in c["groups"]} >= {"Quay", "Water", "Ground"}
+ probe = json.loads((tmp_ws.artifacts / "scene_probe.json").read_text())
+ # the plan's cameras, named as scene_threejs's assembler names them
+ assert [cam["name"] for cam in probe["boot"]["cameras"]] == [to_snake(c.name) for c in plan.cameras[:6]]
+
+
+def test_assemble_leaves_a_failing_zone_out(tmp_ws) -> None:
+ write_fixture(tmp_ws)
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ asm = _rt().assemble(tmp_ws, plan)
+ assert asm.zones_included == ["meadow", "yard"] and set(asm.zones_failed) == {"broken"}
+ assert '"broken"' not in (tmp_ws.src / "scene.py").read_text()
+ assert _rt().build(tmp_ws).ok
+
+
+def test_a_python_driver_fails_the_build_census(tmp_ws) -> None:
+ """D10 behind the lint: a driver whose expression the lint cannot read (built from a variable)
+ still fails the build."""
+ write_fixture(tmp_ws, broken=False)
+ yard = tmp_ws.src / "zones" / "yard.py"
+ yard.write_text(yard.read_text().replace(
+ " return ctx.collection\n",
+ " expr = 'noise.noise(' + '(frame, 0, 0))'\n"
+ " d = cart.driver_add('location', 2).driver\n"
+ " d.expression = expr\n"
+ " return ctx.collection\n"))
+ assert _rt().lint(tmp_ws).passed
+ res = _rt().build(tmp_ws)
+ assert not res.ok and res.error_type == "python_driver" and "Cart_0" in res.error_message
+
+
+def test_a_hero_glb_is_imported_into_ctx_assets(tmp_ws) -> None:
+ write_fixture(tmp_ws, broken=False)
+ write_box_glb(tmp_ws.public / "assets" / "windmill.glb", size=(2.0, 4.0, 2.0))
+ scene = tmp_ws.src / "scene.py"
+ scene.write_text(scene.read_text().replace("HEROES = {}", 'HEROES = {"windmill": "Windmill"}'))
+ yard = tmp_ws.src / "zones" / "yard.py"
+ yard.write_text(yard.read_text().replace(
+ " return ctx.collection\n",
+ " mill = bpy.data.objects.new('Windmill_0', None)\n"
+ " mill.instance_type = 'COLLECTION'\n"
+ " mill.instance_collection = ctx.assets['windmill']\n"
+ " mill.location = (-10.0, 6.0, 2.0)\n"
+ " ctx.collection.objects.link(mill)\n"
+ " return ctx.collection\n"))
+ res = _rt().build(tmp_ws)
+ assert res.ok, res.stdout_tail
+ row = _rows(res)["Windmill_0"]
+ assert row["zone"] == "Yard" and row["supported"] # a 4 m box centred on z = 2 stands on the ground
+
+
+def test_probe_measures_without_touching_build_json(tmp_ws) -> None:
+ write_fixture(tmp_ws, broken=False)
+ rt = _rt()
+ assert rt.build(tmp_ws).ok
+ before = (tmp_ws.artifacts / "build.json").read_text()
+ res = rt.probe(tmp_ws)
+ assert res.ok and res.gate.passed and res.census["placement"]["assets"]
+ assert (tmp_ws.artifacts / "build.json").read_text() == before
+
+
+def test_what_the_render_driver_reads(built) -> None:
+ """The .blend and census the render driver (DESIGN phase 2) is built on: cameras in plan order
+ with their aim, the frame clock, a census in bpy wording with no hero entry for the census GLB."""
+ import subprocess
+
+ ws, res = built
+ assert res.census["language"] == "scene_blender" and res.census["glb_assets"] == []
+ code = ("import bpy, json; s = bpy.context.scene; "
+ "print('C3D', json.dumps([list(s['c3d_cameras']), [list(bpy.data.objects[n]['c3d_look_at']) for n in s['c3d_cameras']], "
+ "s.render.fps, s.frame_start, s.frame_end]))")
+ out = subprocess.run([get_settings().resolve_blender(), "-b", "--factory-startup", str(ws.artifacts / "scene.blend"),
+ "--python-expr", code], capture_output=True, text=True, timeout=120).stdout
+ cams, looks, fps, first, last = json.loads(next(line[4:] for line in out.splitlines() if line.startswith("C3D ")))
+ assert cams == ["overview"] and looks == [[0.0, 0.0, 0.0]] and (fps, first, last) == (30, 1, 46)
diff --git a/harness/tests/scene_blender/test_layout.py b/harness/tests/scene_blender/test_layout.py
new file mode 100644
index 00000000..8b880b78
--- /dev/null
+++ b/harness/tests/scene_blender/test_layout.py
@@ -0,0 +1,169 @@
+"""scene_blender without Blender: the runtime row, the file table, the frame, the skeleton's text
+and the offline census gate (D2 / D10)."""
+
+from __future__ import annotations
+
+import ast
+import re
+
+import pytest
+
+from codeverse3d.contracts.artifacts import Severity
+from codeverse3d.contracts.common import ENTRY_FILE, TRACK_LANGUAGES, Language, Track
+from codeverse3d.contracts.plan import AssetPlan, ScenePlan
+from codeverse3d.conventions import (
+ DRAWS_WARN_SCENE,
+ MAX_DRAWS_SCENE,
+ MAX_TRIS_SCENE,
+ glb_basis,
+ to_authoring_frame,
+)
+from codeverse3d.languages import get_runtime
+from codeverse3d.languages.base import SceneRuntime
+from codeverse3d.languages.scene_blender import frame_of, render_scene_py, write_skeleton
+from codeverse3d.spatial.probes import _census_findings, merge_facts
+from codeverse3d.tracks.planner import plan_example
+
+
+def _plan() -> ScenePlan:
+ return ScenePlan.model_validate(plan_example(Track.SCENE))
+
+
+def test_scene_blender_is_a_scene_language_with_a_runtime() -> None:
+ assert Language.SCENE_BLENDER in TRACK_LANGUAGES[Track.SCENE]
+ rt = get_runtime(Language.SCENE_BLENDER)
+ assert isinstance(rt, SceneRuntime) and rt.language is Language.SCENE_BLENDER
+ assert ENTRY_FILE[Language.SCENE_BLENDER] == "src/scene.py" == rt.entry_globs[0]
+
+
+def test_render_scene_is_not_there_yet(tmp_ws) -> None:
+ """Phase 2 (lane B) lands it; until then a clear error, never a silent empty RenderSet."""
+ with pytest.raises(NotImplementedError, match="phase 2"):
+ get_runtime(Language.SCENE_BLENDER).render_scene(tmp_ws, tmp_ws.artifacts / "renders")
+
+
+def test_the_file_table() -> None:
+ rt = get_runtime(Language.SCENE_BLENDER)
+ plan = _plan()
+ boat = next(a for a in plan.assets if a.name == "FishingBoat")
+ assert rt.zone_file("Quay Front") == "src/zones/quay_front.py"
+ assert rt.asset_file(boat.model_copy(update={"kind": "bpy"})) == "src/assets/fishing_boat.py"
+ assert rt.asset_file(boat.model_copy(update={"kind": "blender_glb"})) == "public/assets/fishing_boat.glb"
+ assert rt.files_for(plan, "Quay") == ["src/zones/quay.py"]
+ assert rt.files_for(plan, "fog") == ["src/env.py"]
+ assert rt.files_for(plan, "cameras") == ["src/scene.py"]
+ assert rt.expected_files(plan) == ["src/scene.py", "src/env.py"]
+
+
+def test_asset_kind_bpy_loads() -> None:
+ """D5: ``AssetPlan.kind`` gains ``bpy``; the old kinds still load."""
+ for kind in ("threejs", "bpy", "blender_glb"):
+ assert AssetPlan(name="Crate", kind=kind, description="a crate", approx_size_m=(1, 1, 1)).kind == kind
+
+
+def test_glb_basis_inverts_to_authoring_frame() -> None:
+ """The census-GLB writer's basis (conventions, handed to Blender on argv) is the inverse of the
+ plan → Blender conversion the skeleton and assembler print: one frame, stated once."""
+ for v in ((1.0, 2.0, 3.0), (-4.5, 0.0, 7.25)):
+ b = to_authoring_frame(v, "scene_blender")
+ back = tuple(sum(r[i] * b[i] for i in range(3)) for r in glb_basis("scene_blender"))
+ assert back == pytest.approx(v)
+ assert glb_basis("scene_threejs") == ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))
+
+
+def test_the_frame_clock() -> None:
+ assert (frame_of(0.0), frame_of(1.5)) == (1, 46)
+
+
+def test_the_assembled_entry_is_data_in_the_blender_frame() -> None:
+ plan = _plan()
+ text = render_scene_py(["quay"], ["bollard"], ["windmill"], plan.cameras[:1])
+ ns: dict = {}
+ exec(compile(ast.parse(text), "scene.py", "exec"), ns) # data only: nothing to call
+ assert ns["ZONES"] == {"quay": "Quay"} and ns["ASSETS"] == {"bollard": "Bollard"} and ns["HEROES"] == {"windmill": "Windmill"}
+ cam, src = ns["CAMERAS"][0], plan.cameras[0]
+ assert cam["location"] == pytest.approx(to_authoring_frame(src.position, "scene_blender"), abs=1e-3)
+ assert cam["look_at"] == pytest.approx(to_authoring_frame(src.look_at, "scene_blender"), abs=1e-3)
+ assert cam["fov"] == src.fov
+
+
+def test_the_skeleton_writes_the_layout(tmp_ws) -> None:
+ plan = _plan()
+ paths = {p.relative_to(tmp_ws.root).as_posix() for p in write_skeleton(tmp_ws, plan)}
+ want = {"src/scene.py", "src/env.py"} | {f"src/zones/{z}.py" for z in ("quay", "water")}
+ want |= {f"src/assets/{a}.py" for a in ("fishing_boat", "bollard")}
+ assert want <= paths
+ for p in paths:
+ compile((tmp_ws.root / p).read_text(), p, "exec")
+ # a Blender object name is global: two zones never place the same <Name>_<i>
+ names = [n for z in ("quay", "water")
+ for n in re.findall(r'place\(ctx, "\w+", "(\w+)"', (tmp_ws.src / "zones" / f"{z}.py").read_text())]
+ assert names
+ assert len(names) == len(set(names))
+
+
+# --------------------------------------------------------------------------- the offline census gate
+def _census(**bpy) -> dict:
+ base = {"totals": {"meshes": 10, "instances": 10, "draws": MAX_DRAWS_SCENE + 1, "triangles": 10, "lights": 0},
+ "groups": [], "fog": None, "background": None}
+ facts = {"lights": 1, "fog": {"type": "VolumeBox"}, "background": "sky:MULTIPLE_SCATTERING", "unique_tris": 10,
+ "instanced_tris": 10, "drivers_invalid": [], "handlers": [], **bpy}
+ return merge_facts(base, facts)
+
+
+def test_bpy_facts_replace_what_the_glb_cannot_carry() -> None:
+ c = _census()
+ assert c["totals"]["lights"] == 1 and c["fog"] == {"type": "VolumeBox"} and c["background"].startswith("sky:")
+ assert c["bpy"]["unique_tris"] == 10 and "fog" not in c["bpy"]
+
+
+def test_offline_draws_are_not_gated_unique_triangles_are() -> None:
+ """D2: the census GLB's draw count describes the writer, not the scene — no draw finding
+ offline however high; the unique-triangle ceiling is an ERROR instead."""
+ kinds = {f.data.get("kind"): f.severity for f in _census_findings(_census(), offline=True)}
+ assert "draw_calls" not in kinds and "unique_tris" not in kinds
+ kinds = {f.data.get("kind"): f.severity for f in _census_findings(_census(unique_tris=MAX_TRIS_SCENE + 1), offline=True)}
+ assert kinds.get("unique_tris") is Severity.ERROR
+ # the same census through the three.js gate still fails on draws (D99 unchanged)
+ online = _census_findings({"totals": {"meshes": 1, "lights": 1, "draws": MAX_DRAWS_SCENE + 1}, "groups": []})
+ assert any(f.data.get("kind") == "draw_calls" and f.severity is Severity.ERROR for f in online)
+ assert DRAWS_WARN_SCENE < MAX_DRAWS_SCENE
+
+
+def test_python_drivers_and_handlers_fail_the_census() -> None:
+ """D10: the build's own check, behind the lint (a driver added by an expression string the
+ lint cannot read still fails here)."""
+ bad = {"id": "object:Mill", "path": "rotation_euler", "index": 1, "expression": "noise.noise((frame,0,0))",
+ "python": True, "valid": False}
+ fs = _census_findings(_census(drivers_invalid=[bad], handlers=["frame_change_pre"]), offline=True)
+ kinds = [(f.data.get("kind"), f.severity) for f in fs]
+ assert ("python_driver", Severity.ERROR) in kinds and ("app_handler", Severity.ERROR) in kinds
+
+
+def test_offline_lamp_check_counts_the_world() -> None:
+ lit = _census_findings(_census(lights=0), offline=True)
+ dark = _census_findings(_census(lights=0, background=None), offline=True)
+ assert not [f for f in lit if "lamps" in f.message]
+ assert [f for f in dark if "lamps" in f.message][0].target == "src/env.py"
+
+
+def test_each_scene_language_plans_its_own_asset_kinds() -> None:
+ """D5: ``bpy`` joins the kinds a plan may hold; the schema a planner is handed stays
+ scene_threejs's (its prompts are byte-identical), a scene_blender planner swaps its own in."""
+ from typing import get_args
+
+ from codeverse3d.contracts.plan import SCENE_ASSET_KINDS
+
+ kinds = set(get_args(AssetPlan.model_fields["kind"].annotation))
+ assert {lang.value for lang in TRACK_LANGUAGES[Track.SCENE]} == set(SCENE_ASSET_KINDS)
+ assert all(set(v) <= kinds for v in SCENE_ASSET_KINDS.values())
+ enum = ScenePlan.model_json_schema()["$defs"]["AssetPlan"]["properties"]["kind"]["enum"]
+ assert enum == list(SCENE_ASSET_KINDS["scene_threejs"])
+
+
+def test_the_adapter_and_the_host_agree_on_the_census_url() -> None:
+ from codeverse3d.config import get_settings
+
+ lib = get_settings().runtime_js_dir() / "lib"
+ url = re.search(r"CENSUS_GLB_URL = '([^']+)'", (lib / "glb_scene.mjs").read_text()).group(1)
+ assert f"'{url}': {{ body: fs.readFileSync(glb)" in (lib / "host_env.mjs").read_text()
diff --git a/harness/tests/scene_blender/test_lint.py b/harness/tests/scene_blender/test_lint.py
new file mode 100644
index 00000000..2b7c14e3
--- /dev/null
+++ b/harness/tests/scene_blender/test_lint.py
@@ -0,0 +1,138 @@
+"""The scene_blender lint table: the object track's bpy traps + the scene policy (DESIGN §8, D10)."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse3d.contracts.artifacts import Severity
+from codeverse3d.contracts.common import Track
+from codeverse3d.contracts.plan import ScenePlan
+from codeverse3d.languages._ast_lint import BASE_FORBIDDEN_IMPORTS
+from codeverse3d.languages.scene_blender import (
+ FORBIDDEN_IMPORTS,
+ lint,
+ lint_scene_source,
+ simple_driver,
+ write_skeleton,
+)
+from codeverse3d.tracks.planner import plan_example
+
+HEAD = "import bpy\n\n\ndef build(ctx):\n"
+
+
+def _zone(body: str) -> str:
+ return HEAD + "".join(f" {line}\n" for line in body.splitlines()) + " return ctx.collection\n"
+
+
+def _hits(source: str, *, role: str = "zone", target: str = "src/zones/yard.py") -> dict[str, Severity]:
+ return {f.message: f.severity for f in lint_scene_source(source, target=target, role=role)}
+
+
+def _worst(source: str, **kw) -> Severity | None:
+ sev = set(_hits(source, **kw).values())
+ for s in (Severity.ERROR, Severity.WARN, Severity.INFO):
+ if s in sev:
+ return s
+ return None
+
+
+# (body inside a zone's build(ctx), the worst severity the lint must give it)
+TABLE = [
+ # D10: a Python driver never evaluates under --factory-startup (it reads 0) -> ERROR
+ ('d = ob.driver_add("location", 2).driver\nd.expression = "noise.noise((frame, 0, 0))"', Severity.ERROR),
+ ('d = ob.driver_add("location", 2).driver\nd.expression = "bpy.data.objects[0].location.x"', Severity.ERROR),
+ ('d = ob.driver_add("location", 2).driver\nd.expression = "frame ** 2"', Severity.ERROR),
+ ('d = ob.driver_add("location", 2).driver\nd.use_self = True', Severity.ERROR),
+ ('d = ob.driver_add("location", 2).driver\nd.expression = "sin(frame * 0.2) * 2 if frame > 3 else 0"', None),
+ ("bpy.app.handlers.frame_change_pre.append(lambda s: None)", Severity.ERROR),
+ # harness-owned: rendering, files, cameras, frames, scene render settings
+ ("bpy.ops.render.render(write_still=True)", Severity.ERROR),
+ ('bpy.ops.wm.save_as_mainfile(filepath="x.blend")', Severity.ERROR),
+ ('bpy.ops.import_scene.gltf(filepath="x.glb")', Severity.ERROR),
+ ('cam = bpy.data.cameras.new("C")', Severity.ERROR),
+ ('ctx.scene.render.engine = "CYCLES"', Severity.ERROR),
+ ("ctx.scene.cycles.samples = 64", Severity.ERROR),
+ ('ctx.scene.view_settings.view_transform = "AgX"', Severity.ERROR),
+ ("ctx.scene.frame_end = 100", Severity.ERROR),
+ ("ctx.scene.frame_set(10)", Severity.ERROR),
+ ("ctx.scene.camera = None", Severity.ERROR),
+ ('open("x.txt", "w")', Severity.ERROR),
+ # the world is env.py's
+ ('ctx.scene.world = bpy.data.worlds.new("W")', Severity.ERROR),
+ # renamed / removed API
+ ('sky.sky_type = "NISHITA"', Severity.ERROR),
+ ('bsdf.inputs["Specular"].default_value = 0.5', Severity.ERROR),
+ ("me.calc_normals()", Severity.ERROR),
+ # determinism: ctx.rng(seed) is the only randomness
+ ("import random\nx = random.uniform(0, 1)", Severity.ERROR),
+ ("import random\nr = random.Random()", Severity.ERROR),
+ ("import numpy as np\nx = np.random.rand(3)", Severity.ERROR),
+ ("rng = ctx.rng(7)\nx = rng.uniform(0, 1)", None),
+ ("import random\nr = random.Random(3)\nx = r.uniform(0, 1)", None),
+ ("import numpy as np\ng = np.random.default_rng(3)", None),
+ # build time and zone ownership
+ ("for i in range(50):\n bpy.ops.mesh.primitive_cube_add(size=1, location=(i, 0, 0))", Severity.WARN),
+ ("ctx.scene.collection.objects.link(ob)", Severity.WARN),
+ # the agent's own settings on its own data are NOT harness-owned
+ ("mod.render_levels = 2", None),
+ ('mat.cycles.displacement_method = "BOTH"', None),
+ ("ctx.collection.objects.link(ob)", None),
+ ('ob["placement"] = "free"', None),
+]
+
+
[email protected](("body", "worst"), TABLE, ids=[t[0].splitlines()[-1][:48] for t in TABLE])
+def test_the_scene_lint_table(body: str, worst: Severity | None) -> None:
+ assert _worst(_zone(body)) is worst, _hits(_zone(body))
+
+
[email protected]("mod", ["os", "sys", "time", "datetime", "pathlib", "subprocess", "socket"])
+def test_clock_file_and_process_imports_are_forbidden(mod: str) -> None:
+ assert _worst(f"import {mod}\n" + _zone("pass")) is Severity.ERROR
+ assert BASE_FORBIDDEN_IMPORTS <= FORBIDDEN_IMPORTS
+
+
+def test_the_world_and_lamps_belong_to_env() -> None:
+ env = ("import bpy\n\n\ndef height_at(x, y):\n return 0.0\n\n\ndef build_env(ctx):\n"
+ ' ctx.scene.world = bpy.data.worlds.new("Sky")\n'
+ ' ctx.collection.objects.link(bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN")))\n'
+ " return {}\n")
+ assert _worst(env, role="env", target="src/env.py") is None
+ assert _worst(env.replace("def build_env", "def make_env"), role="env", target="src/env.py") is Severity.ERROR
+
+
+def test_module_exports_are_the_layout() -> None:
+ assert _worst("import bpy\n\n\ndef make(ctx):\n return ctx.collection\n") is Severity.ERROR # zone: build
+ asset = "import bpy\n\n\ndef build_crate(ctx, variant=0):\n return ctx.collection\n"
+ assert _worst(asset, role="asset", target="src/assets/crate.py") is None
+ assert _worst(asset, role="asset", target="src/assets/barrel.py") is Severity.ERROR
+
+
+def test_simple_driver_is_blenders_subset() -> None:
+ """Verified against Blender 5.0.1 ``driver.is_simple_expression`` (DESIGN probes/drv.py)."""
+ for ok in ("sin(frame*0.2)*2", "frame*2 if frame > 3 else 1", "clamp(frame / 40, 0, 1)", "lerp(0, 2, 0.5)", "pi", "not frame"):
+ assert simple_driver(ok), ok
+ for bad in ("frame ** 2", "frame % 3", "noise.noise((frame, 0, 0))", "hypot(frame, 1)", "'a'", "[frame]", "sin(x=1)"):
+ assert not simple_driver(bad), bad
+
+
+def test_the_library_is_not_the_agents_code(tmp_ws) -> None:
+ """``src/lib/`` is harness-owned (D51): syntax only, never the policy."""
+ (tmp_ws.src / "lib").mkdir(parents=True)
+ (tmp_ws.src / "lib" / "sky.py").write_text("import os\nX = os.getcwd()\n")
+ (tmp_ws.src / "scene.py").write_text("ZONES = {}\nASSETS = {}\nHEROES = {}\nCAMERAS = []\n")
+ assert lint(tmp_ws).passed
+ (tmp_ws.src / "lib" / "sky.py").write_text("def broken(:\n")
+ assert not lint(tmp_ws).passed
+
+
+def test_the_skeleton_lints_clean(tmp_ws) -> None:
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ write_skeleton(tmp_ws, plan)
+ rep = lint(tmp_ws)
+ assert rep.passed and not [f for f in rep.findings if f.severity is not Severity.INFO], rep.findings
+
+
+def test_a_missing_entry_is_a_lint_error(tmp_ws) -> None:
+ rep = lint(tmp_ws)
+ assert not rep.passed and rep.errors[0].target == "src/scene.py"
diff --git a/harness/tests/scene_gates/test_draw_budget.py b/harness/tests/scene_gates/test_draw_budget.py
index 668e87d3..17936863 100644
--- a/harness/tests/scene_gates/test_draw_budget.py
+++ b/harness/tests/scene_gates/test_draw_budget.py
@@ -93,13 +93,13 @@ def test_a_probe_with_no_boot_record_is_a_harness_failure_not_a_verdict() -> Non
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
+ from codeverse3d.spatial.probes import probe_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, {})
+ r = probe_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"
@@ -107,5 +107,5 @@ def test_a_harness_failure_finding_makes_the_probe_result_not_ok() -> None:
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": {}})
+ r2 = probe_result(real, {"totals": {}})
assert r2.ok is True and r2.errors == [] and len(r2.findings) == 1