Skip to content

Official Codebase of 3DCodeVerse

Python

languages: seven packages become seven modules

gaoypeng70cb7e6b4c72
diff --git a/harness/codeverse/languages/base.py b/harness/codeverse/languages/base.py
index 47801058..95273359 100644
--- a/harness/codeverse/languages/base.py
+++ b/harness/codeverse/languages/base.py
@@ -45,29 +45,29 @@ class LanguageRuntime(Protocol):
def get_runtime(language: Language | str) -> LanguageRuntime:
lang = Language(language)
if lang is Language.BLENDER:
- from codeverse.languages.blender.runtime import BlenderRuntime
+ from codeverse.languages.blender import BlenderRuntime
return BlenderRuntime()
if lang is Language.CADQUERY:
- from codeverse.languages.cadquery.runtime import CadQueryRuntime
+ from codeverse.languages.cadquery import CadQueryRuntime
return CadQueryRuntime()
if lang is Language.THREEJS:
- from codeverse.languages.threejs.runtime import ThreeJsRuntime
+ from codeverse.languages.threejs import ThreeJsRuntime
return ThreeJsRuntime()
if lang is Language.URDF_BLENDER:
- from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+ from codeverse.languages.urdf import UrdfBlenderRuntime
return UrdfBlenderRuntime()
if lang is Language.GLSL_SHADER:
- from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
+ from codeverse.languages.glsl_shader import GlslShaderRuntime
return GlslShaderRuntime()
if lang is Language.OPENGL_PYTHON:
- from codeverse.languages.opengl_python.runtime import OpenGLPythonRuntime
+ from codeverse.languages.opengl_python import OpenGLPythonRuntime
return OpenGLPythonRuntime()
- from codeverse.languages.scene_threejs.runtime import SceneThreeJsRuntime
+ from codeverse.languages.scene_threejs import SceneThreeJsRuntime
return SceneThreeJsRuntime()
diff --git a/harness/codeverse/languages/blender/__init__.py b/harness/codeverse/languages/blender/__init__.py
index 1bcfe7ff..84a280d7 100644
--- a/harness/codeverse/languages/blender/__init__.py
+++ b/harness/codeverse/languages/blender/__init__.py
@@ -1,31 +1,830 @@
"""Blender (bpy) language: runtime, lint, layout, skeleton; wrappers run inside Blender."""
-from codeverse.languages.blender.layout import (
- build_fn_name,
- lint_workspace,
- part_file_rel,
- part_files,
+from __future__ import annotations
+
+import ast
+import math
+import os
+import re
+import time
+from pathlib import Path
+
+from codeverse.config import Settings, get_settings
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.plan import BBox, PartPlan, Plan, StaticPlan
+from codeverse.conventions import MAX_TRIS_OBJECT, to_pascal, to_snake
+from codeverse.languages._ast_lint import ( # noqa: F401 — dotted re-exported
+ BASE_FORBIDDEN_IMPORTS,
+ check_imports,
+ describe_parse_failure,
+ dotted,
+ safe_parse,
+)
+from codeverse.languages._common import (
+ compose_build_result,
+ run_subprocess,
+ strip_blender_noise,
+)
+from codeverse.proc import scrub_secrets
+from codeverse.prompts import PROMPTS_DIR
+from codeverse.workspace import Workspace
+
+# ===================================================================== lint
+# (merged from codeverse/languages/blender/lint.py, 2026-08-28)
+GATE = "lint:blender"
+
+ALLOWED_IMPORTS = {
+ "bpy", "bmesh", "mathutils", "math", "random", "numpy", "np", "itertools", "functools",
+ "collections", "typing", "dataclasses", "colorsys", "statistics", "operator", "enum", "copy",
+ # os/sys are deliberately ALLOWED here (unlike cadquery/opengl): headless bpy scripts
+ # touch them legitimately and the forbidden-call rules below catch the harmful uses.
+ "sys", "os", "__future__", "bpy_extras",
+ "parts", # the workspace's own src/parts/<snake>.py modules (multi-file layout)
+}
+FORBIDDEN_IMPORTS = frozenset(BASE_FORBIDDEN_IMPORTS | {"pathlib"})
+# dotted-name prefixes of calls that violate the contract (harness owns them)
+FORBIDDEN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
+ ("bpy.ops.render.", "rendering is done by the harness; delete all bpy.ops.render.* calls"),
+ ("bpy.ops.export_", "export is done by the harness; delete all bpy.ops.export_* calls"),
+ ("bpy.ops.import_", "no imports of external files; build geometry procedurally"),
+ ("bpy.ops.wm.", "no bpy.ops.wm.* (file open/save/append/link/quit); the harness owns the file"),
+ ("bpy.ops.image.save", "no image file writes"),
+ ("bpy.data.libraries.", "no linking/appending external .blend data"),
+ ("os.system", "no shell commands"),
+ ("os.remove", "no file IO"), ("os.unlink", "no file IO"), ("os.rmdir", "no file IO"),
+ ("os.makedirs", "no file IO"), ("os.mkdir", "no file IO"), ("os.rename", "no file IO"),
+ ("subprocess.", "no subprocesses"),
+ ("urllib.", "no network"), ("requests.", "no network"),
+ ("shutil.", "no file IO"),
)
-from codeverse.languages.blender.lint import lint_blender_file, lint_blender_source
-from codeverse.languages.blender.runtime import BlenderNotFoundError, BlenderRuntime
-from codeverse.languages.blender.skeleton import (
- blender_skeleton_source,
- model_file_source,
- part_file_source,
- write_blender_skeleton,
+WARN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
+ ("bpy.data.cameras.new", "the harness owns cameras; remove camera creation"),
+ ("bpy.ops.object.camera_add", "the harness owns cameras; remove camera creation"),
+ ("bpy.data.lights.new", "the harness owns lighting; remove light creation"),
+ ("bpy.ops.object.light_add", "the harness owns lighting; remove light creation"),
+ ("bpy.data.worlds.new", "the harness owns the world/background; remove world code"),
+ ("bpy.ops.view3d.", "view3d operators fail in background mode (no 3D viewport)"),
+ ("bpy.ops.screen.", "screen operators fail in background mode"),
+ ("sys.exit", "do not exit; let the script fall off the end"),
+)
+# Principled BSDF inputs that raise KeyError in Blender 4.x/5.x → their replacement.
+# Verified against Blender 5.0.1: 'Anisotropic' and 'Specular Tint' STILL EXIST (do not list them).
+REMOVED_BSDF_INPUTS = {
+ "Specular": "Specular IOR Level", "Subsurface": "Subsurface Weight", "Transmission": "Transmission Weight",
+ "Emission": "Emission Color (+ 'Emission Strength')", "Subsurface Color": "Base Color (subsurface tint removed)",
+ "Clearcoat": "Coat Weight", "Clearcoat Roughness": "Coat Roughness", "Sheen": "Sheen Weight",
+ "Transmission Roughness": "(removed) use Roughness",
+}
+KNOWN_BINDINGS = ("Vector", "Matrix", "Euler", "Quaternion", "bmesh", "math", "random", "np", "numpy", "bpy")
+PASCAL_RE = re.compile(r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*(?:_\d+)?$")
+
+
+class _Collector(ast.NodeVisitor):
+ """One pass over the tree; rules read the collected facts."""
+
+ def __init__(self) -> None:
+ self.imports: dict[str, int] = {} # top-level module → line
+ self.bound: set[str] = set()
+ self.calls: list[tuple[str, ast.Call]] = []
+ self.attr_stores: list[tuple[str, int]] = [] # dotted target of assignments
+ self.name_loads: list[tuple[str, int]] = []
+ self.bm_names: set[str] = set() # names bound from bmesh.new() / bmesh.from_edit_mesh()
+ self.bm_subscripts: list[tuple[str, int]] = [] # (base name, line) of <name>.verts/edges/faces[i]
+ self.bsdf_inputs: list[tuple[str, int]] = []
+ self.names_assigned: list[str] = [] # string constants assigned to .name / name=
+ self.constants: list[tuple[str, int]] = []
+ self.has_temp_override = False
+ self.keywords: list[tuple[str, int]] = []
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ top = a.name.split(".")[0]
+ self.imports.setdefault(top, node.lineno)
+ self.bound.add((a.asname or a.name).split(".")[0])
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ top = (node.module or "").split(".")[0]
+ self.imports.setdefault(top, node.lineno)
+ for a in node.names:
+ self.bound.add(a.asname or a.name)
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ self.bound.add(node.name)
+ for a in node.args.args + node.args.kwonlyargs + node.args.posonlyargs:
+ self.bound.add(a.arg)
+ if node.args.vararg:
+ self.bound.add(node.args.vararg.arg)
+ if node.args.kwarg:
+ self.bound.add(node.args.kwarg.arg)
+ self.generic_visit(node)
+
+ visit_AsyncFunctionDef = visit_FunctionDef # type: ignore[assignment]
+
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
+ self.bound.add(node.name)
+ self.generic_visit(node)
+
+ def visit_Name(self, node: ast.Name) -> None:
+ if isinstance(node.ctx, ast.Load):
+ self.name_loads.append((node.id, node.lineno))
+ else:
+ self.bound.add(node.id)
+
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
+ if node.name:
+ self.bound.add(node.name)
+ self.generic_visit(node)
+
+ def visit_Call(self, node: ast.Call) -> None:
+ name = dotted(node.func)
+ self.calls.append((name, node))
+ if name.endswith("temp_override"):
+ self.has_temp_override = True
+ for a in node.args:
+ if isinstance(a, ast.Constant) and isinstance(a.value, str):
+ self.names_assigned.append(a.value)
+ for kw in node.keywords:
+ if kw.arg:
+ self.keywords.append((kw.arg, node.lineno))
+ if kw.arg == "name" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
+ self.names_assigned.append(kw.value.value)
+ self.generic_visit(node)
+
+ def visit_Assign(self, node: ast.Assign) -> None:
+ for t in node.targets:
+ d = dotted(t)
+ if d:
+ self.attr_stores.append((d, node.lineno))
+ v = node.value
+ if isinstance(v, ast.Call) and dotted(v.func) in ("bmesh.new", "bmesh.from_edit_mesh"):
+ self.bm_names.update(t.id for t in node.targets if isinstance(t, ast.Name))
+ if isinstance(v, ast.Constant) and isinstance(v.value, str):
+ self.names_assigned.append(v.value)
+ elif isinstance(v, ast.JoinedStr) and v.values and isinstance(v.values[0], ast.Constant):
+ self.names_assigned.append(str(v.values[0].value).rstrip("_"))
+ self.generic_visit(node)
+
+ def visit_Subscript(self, node: ast.Subscript) -> None:
+ if isinstance(node.value, ast.Attribute):
+ # only <Name>.verts/edges/faces[i] — e.verts[0] (BMEdge) / me.edges[i] (Mesh) are
+ # filtered later against the names actually bound to a bmesh (BMElemSeq).
+ if (node.value.attr in ("verts", "edges", "faces") and not isinstance(node.slice, ast.Slice)
+ and isinstance(node.value.value, ast.Name)):
+ self.bm_subscripts.append((node.value.value.id, node.lineno))
+ if node.value.attr == "inputs" and isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, str):
+ self.bsdf_inputs.append((node.slice.value, node.lineno))
+ self.generic_visit(node)
+
+ def visit_Constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, str):
+ self.constants.append((node.value, node.lineno))
+
+
+def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target: str = "src/model.py") -> GateFinding:
+ data = {"line": line} if line else {}
+ 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]:
+ 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(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(E, f"forbidden import `{mod}`", line, "only bpy/bmesh/mathutils/math/random/numpy (+stdlib data helpers) are allowed")
+ return _f(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(E, f"forbidden call `{name}`", call.lineno, hint))
+ for prefix, hint in WARN_CALL_PREFIXES:
+ if name.startswith(prefix):
+ out.append(_f(W, f"`{name}` — {hint}", call.lineno, hint))
+ if name == "open":
+ out.append(_f(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(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(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(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(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)`"))
+ if name.endswith("bpy.ops.object.join") or name == "bpy.ops.object.join":
+ out.append(_f(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(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(E, "Mesh.calc_normals() was removed in 4.0 (normals are computed automatically)", call.lineno, "delete the call (use me.update() if needed)"))
+ if name == "bpy.ops.wm.redraw_timer":
+ pass
+ for target, line in c.attr_stores:
+ if target.endswith(".use_auto_smooth") or target.endswith(".auto_smooth_angle"):
+ out.append(_f(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(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(W, f"`{target}` assignment — cameras/world are owned by the harness", line, "remove camera/world code"))
+ if target.endswith(".use_nodes"):
+ out.append(_f(I, "`use_nodes = True` is a no-op in Blender 5.x (materials always have a node tree); harmless", line, ""))
+ for key, line in c.bsdf_inputs:
+ if key in REMOVED_BSDF_INPUTS:
+ out.append(_f(E, f"Principled BSDF input '{key}' does not exist in Blender 4.x/5.x (KeyError at runtime)", line,
+ f"use inputs['{REMOVED_BSDF_INPUTS[key]}']"))
+ elif key == "Specular Tint":
+ out.append(_f(I, "'Specular Tint' is an RGBA colour in Blender 4.x/5.x (a float raises TypeError)", line,
+ 'assign a 4-tuple: inputs["Specular Tint"].default_value = (r, g, b, 1.0)'))
+ has_lookup = any(n.endswith("ensure_lookup_table") for n, _ in c.calls)
+ # only subscripts on a BMESH object need ensure_lookup_table (BMElemSeq); e.verts[0]
+ # (BMEdge/BMFace tuples) and me.edges[i] (Mesh collections) are always fine.
+ bm_subs = [line for base, line in c.bm_subscripts if base in c.bm_names or base == "bm"]
+ if "bmesh" in c.imports and bm_subs and not has_lookup:
+ out.append(_f(E, "bmesh verts/edges/faces indexed with [] but ensure_lookup_table() is never called → IndexError", bm_subs[0],
+ "after bm.from_mesh()/any topology change call `bm.verts.ensure_lookup_table(); bm.edges.ensure_lookup_table(); bm.faces.ensure_lookup_table()` before indexing"))
+ for name, line in c.name_loads:
+ if name in KNOWN_BINDINGS and name not in c.bound:
+ hint = {"Vector": "from mathutils import Vector", "Matrix": "from mathutils import Matrix", "Euler": "from mathutils import Euler",
+ "Quaternion": "from mathutils import Quaternion", "np": "import numpy as np", "numpy": "import numpy"}.get(name, f"import {name}")
+ out.append(_f(E, f"`{name}` is used but never imported (NameError at runtime)", line, hint))
+ break
+ if "bpy.context.selected_objects" in source:
+ out.append(_f(W, "bpy.context.selected_objects is unreliable in background mode (often empty)", None,
+ "keep references to the objects you create (`obj = bpy.context.object` right after primitive_*_add) instead of re-reading the selection"))
+ for const, line in c.constants:
+ if const == "BLENDER_EEVEE_NEXT":
+ out.append(_f(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"))
+ 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(I, f"named objects: {sorted(set(pascal))[:12]}", None, ""))
+ elif expect_names:
+ out.append(_f(W, "no PascalCase object names found (e.g. obj.name = 'SeatCushion')", None,
+ "name every visible mesh after its part: `obj.name = 'SeatCushion'`; instances `Leg_0..Leg_3`"))
+ return out
+
+
+def lint_blender_source(
+ source: str, *, target: str = "src/model.py", expect_names: bool = True, expect_bpy: bool = True,
+) -> GateReport:
+ """Lint one bpy script; returns ``GateReport(gate='lint:blender')``.
+
+ ``expect_names=False`` silences the PascalCase-name warning (multi-file entry files
+ only import and call builders); ``expect_bpy=False`` allows helper modules that do
+ not touch bpy. :func:`codeverse.languages.blender.lint_workspace` lints a
+ whole ``src/`` tree with these set per file.
+ """
+ t0 = time.monotonic()
+ findings: list[GateFinding] = []
+ tree, exc = safe_parse(source, target)
+ if tree is None:
+ msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
+ findings.append(_f(Severity.ERROR, msg, line, hint, target))
+ return GateReport(gate=GATE, passed=False, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
+ c = _Collector()
+ c.visit(tree)
+ findings = _rules(c, source, target=target, expect_names=expect_names, expect_bpy=expect_bpy)
+ for f in findings:
+ f.target = target
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
+
+
+def lint_blender_file(path: Path, *, target: str = "src/model.py") -> GateReport:
+ if not path.is_file():
+ return GateReport(gate=GATE, passed=False, findings=[_f(Severity.ERROR, f"{target} is missing", None, "create src/model.py (see the skeleton)", target)])
+ return lint_blender_source(path.read_text(), target=target)
+
+
+# ===================================================================== layout
+# (merged from codeverse/languages/blender/layout.py, 2026-08-28)
+ENTRY_REL = ENTRY_FILE[Language.BLENDER] # "src/model.py"
+PARTS_DIR = "parts"
+PARTS_PKG = "parts"
+
+
+def part_file_rel(part_name: str) -> str:
+ """``'Seat Cushion'`` → ``'src/parts/seat_cushion.py'`` (workspace-relative)."""
+ return f"src/{PARTS_DIR}/{to_snake(part_name)}.py"
+
+
+def build_fn_name(part_name: str) -> str:
+ """``'SeatCushion'`` → ``'build_seat_cushion'`` (the function a part file must export)."""
+ return f"build_{to_snake(part_name)}"
+
+
+def part_files(ws: Workspace) -> list[Path]:
+ """Part modules present in the workspace (sorted; underscore helper modules excluded)."""
+ d = ws.src / PARTS_DIR
+ if not d.is_dir():
+ return []
+ return sorted(p for p in d.glob("*.py") if not p.name.startswith("_"))
+
+
+def helper_files(ws: Workspace) -> list[Path]:
+ """Underscore-prefixed shared modules under ``src/parts/`` (linted, not required to export)."""
+ d = ws.src / PARTS_DIR
+ return sorted(d.glob("_*.py")) if d.is_dir() else []
+
+
+def source_files(ws: Workspace) -> list[Path]:
+ """Every agent-authored python file under ``src/`` (entry first), including nested dirs."""
+ entry = ws.src / "model.py"
+ rest = sorted(p for p in ws.src.rglob("*.py") if p != entry)
+ return ([entry] if entry.is_file() else []) + rest
+
+
+def _rel(ws: Workspace, p: Path) -> str:
+ return p.relative_to(ws.root).as_posix()
+
+
+def _finding(sev: Severity, target: str, msg: str, hint: str, line: int | None = None) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint,
+ data={"line": line} if line else {})
+
+
+def _exported_functions(tree: ast.Module) -> set[str]:
+ return {n.name for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+
+
+def _imported_part_modules(tree: ast.Module) -> set[str]:
+ """snake names of ``parts.<snake>`` modules the entry references via import statements."""
+ out: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.module:
+ dotted = node.module.split(".")
+ if dotted[0] == PARTS_PKG:
+ if len(dotted) > 1:
+ out.add(dotted[1])
+ else: # ``from parts import seat, leg``
+ out.update(a.name for a in node.names)
+ elif isinstance(node, ast.Import):
+ for a in node.names:
+ dotted = a.name.split(".")
+ if dotted[0] == PARTS_PKG and len(dotted) > 1:
+ out.add(dotted[1])
+ return out
+
+
+def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | None) -> list[GateFinding]:
+ """Cross-file rules: naming, exported builders, import-time side effects, unused part files."""
+ out: list[GateFinding] = []
+ E, W = Severity.ERROR, Severity.WARN
+ imported = _imported_part_modules(entry_tree) if entry_tree is not None else set()
+ for p in parts:
+ target = _rel(ws, p)
+ stem = p.stem
+ if stem != to_snake(stem):
+ out.append(_finding(E, target, f"part file name '{p.name}' is not snake_case",
+ f"rename to src/{PARTS_DIR}/{to_snake(stem)}.py (the harness maps plan part "
+ f"'{stem}' → that file) and fix the import in model.py"))
+ continue
+ try:
+ tree = ast.parse(p.read_text(), filename=target)
+ except SyntaxError:
+ continue # reported by the per-file lint
+ fn = f"build_{stem}"
+ if fn not in _exported_functions(tree):
+ out.append(_finding(E, target, f"{target} does not define `def {fn}()`",
+ f"every part file exports `def {fn}() -> bpy.types.Object` returning the named object "
+ f"at its world pose; model.py calls it (`from {PARTS_PKG}.{stem} import {fn}`)"))
+ for node in tree.body:
+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
+ name = getattr(node.value.func, "id", "")
+ if name.startswith("build_") or name == "main":
+ out.append(_finding(W, target, f"{target} calls `{name}()` at import time",
+ "part files only DEFINE builders; model.py calls them once (a module-level "
+ "call here builds the part twice → auto-suffixed 'Name.001')", node.lineno))
+ if entry_tree is not None and stem not in imported:
+ out.append(_finding(W, target, f"{target} is never imported by src/model.py → its part is not built",
+ f"add `from {PARTS_PKG}.{stem} import {fn}` to model.py and call `{fn}()` in main()"))
+ return out
+
+
+def lint_workspace(ws: Workspace) -> GateReport:
+ """Lint every python file under ``src/`` + the multi-file layout rules (one merged report)."""
+ t0 = time.monotonic()
+ entry = ws.src / "model.py"
+ if not entry.is_file():
+ return GateReport(gate=GATE, passed=False, duration_ms=0, findings=[_finding(
+ Severity.ERROR, ENTRY_REL, f"{ENTRY_REL} is missing",
+ "create src/model.py (entry: imports src/parts/<snake>.py builders and calls them; see the skeleton)")])
+ parts = part_files(ws)
+ findings: list[GateFinding] = []
+ for p in source_files(ws):
+ target = _rel(ws, p)
+ is_entry = p == entry
+ is_helper = p.name.startswith("_")
+ rep = lint_blender_source(p.read_text(), target=target,
+ expect_names=not (is_helper or (is_entry and bool(parts))),
+ expect_bpy=not is_helper)
+ findings.extend(rep.findings)
+ entry_tree: ast.Module | None
+ try:
+ entry_tree = ast.parse(entry.read_text(), filename=ENTRY_REL)
+ except SyntaxError:
+ entry_tree = None
+ findings.extend(_layout_rules(ws, parts, entry_tree))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
+
+
+# ===================================================================== skeleton
+# (merged from codeverse/languages/blender/skeleton.py, 2026-08-28)
+# keyword → (rgb, roughness, metallic) placeholder finishes so the first render is not all-grey
+_FINISHES: tuple[tuple[tuple[str, ...], tuple[float, float, float], float, float], ...] = (
+ (("wood", "oak", "walnut", "pine", "timber", "birch"), (0.55, 0.36, 0.20), 0.55, 0.0),
+ (("steel", "chrome", "aluminium", "aluminum", "metal", "iron", "brass"), (0.75, 0.75, 0.78), 0.35, 1.0),
+ (("fabric", "cloth", "cushion", "upholster", "velvet", "linen"), (0.45, 0.30, 0.30), 0.9, 0.0),
+ (("leather",), (0.30, 0.16, 0.10), 0.6, 0.0),
+ (("glass", "acrylic"), (0.85, 0.9, 0.95), 0.05, 0.0),
+ (("rubber", "tire", "tyre"), (0.05, 0.05, 0.05), 0.9, 0.0),
+ (("plastic", "abs", "nylon"), (0.9, 0.9, 0.9), 0.4, 0.0),
+ (("black",), (0.05, 0.05, 0.05), 0.5, 0.0),
+ (("white",), (0.9, 0.9, 0.9), 0.5, 0.0),
+ (("red",), (0.7, 0.1, 0.1), 0.5, 0.0),
+ (("blue",), (0.1, 0.2, 0.7), 0.5, 0.0),
+ (("green",), (0.1, 0.5, 0.2), 0.5, 0.0),
)
-__all__ = [
- "BlenderNotFoundError",
- "BlenderRuntime",
- "blender_skeleton_source",
- "build_fn_name",
- "lint_blender_file",
- "lint_blender_source",
- "lint_workspace",
- "model_file_source",
- "part_file_rel",
- "part_file_source",
- "part_files",
- "write_blender_skeleton",
-]
+
+def finish_for(text: str) -> tuple[tuple[float, float, float], float, float]:
+ """Placeholder (rgb, roughness, metallic) from material words; neutral grey otherwise."""
+ low = text.lower()
+ for words, rgb, rough, metal in _FINISHES:
+ if any(w in low for w in words):
+ return rgb, rough, metal
+ return (0.6, 0.6, 0.6), 0.5, 0.0
+
+
+def instance_centers(bbox: BBox, n: int, symmetry: str) -> list[tuple[float, float, float]]:
+ """Placeholder centres for ``n`` instances of a part using the plan's symmetry hint."""
+ cx, cy, cz = bbox.center
+ if n <= 1:
+ return [(cx, cy, cz)]
+ if n == 2 and symmetry == "mirror_x":
+ return [(abs(cx), cy, cz), (-abs(cx), cy, cz)]
+ if n == 2 and symmetry == "mirror_y":
+ return [(cx, abs(cy), cz), (cx, -abs(cy), cz)]
+ if n == 4 and symmetry in ("mirror_x", "mirror_y"):
+ ax, ay = abs(cx), abs(cy)
+ return [(ax, -ay, cz), (-ax, -ay, cz), (-ax, ay, cz), (ax, ay, cz)]
+ if symmetry == "radial":
+ r = math.hypot(cx, cy)
+ a0 = math.atan2(cy, cx)
+ return [(r * math.cos(a0 + 2 * math.pi * i / n), r * math.sin(a0 + 2 * math.pi * i / n), cz) for i in range(n)]
+ return [(cx, cy, cz) for _ in range(n)]
+
+
+def _fmt(v: tuple[float, float, float]) -> str:
+ return "(" + ", ".join(f"{x:.3f}" for x in v) + ")"
+
+
+def _bevel(bbox: BBox) -> float:
+ return max(0.0, min(0.01, 0.08 * min(bbox.extents)))
+
+
+# ----------------------------------------------------------------------------- shared text blocks
+IMPORTS = '''import math
+import random
+
+import bpy
+import bmesh # noqa: F401 (available for custom meshes: bm = bmesh.new(); ... bm.to_mesh(me))
+from mathutils import Vector, Matrix # noqa: F401
+
+random.seed(0)
+'''
+
+HELPERS = '''
+# ----------------------------------------------------------------------------- helpers (plain bpy)
+def make_material(name, rgb, roughness=0.5, metallic=0.0):
+ """Principled BSDF material with flat PBR values (what the GLB keeps)."""
+ 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 add_box(name, center, extents, material=None, bevel=0.0):
+ """Axis-aligned box: size=1 cube scaled to `extents`, scale baked into the mesh."""
+ bpy.ops.mesh.primitive_cube_add(size=1, location=center, scale=extents)
+ obj = bpy.context.object
+ obj.name = name
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+ if material is not None:
+ obj.data.materials.append(material)
+ if bevel > 0:
+ mod = obj.modifiers.new("Bevel", "BEVEL")
+ mod.width = bevel
+ mod.segments = 3
+ mod.limit_method = "ANGLE"
+ return obj
+
+'''
+
+SELFCHECK = '''
+def _selfcheck():
+ """What the harness checks first: meshes exist, no auto-suffixed names, stands on z=0."""
+ bpy.context.view_layer.update()
+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]
+ assert meshes, "no mesh objects built"
+ for o in meshes:
+ assert "." not in o.name, f"auto-suffixed name {o.name!r}: give every instance its own name"
+ z_min = min((o.matrix_world @ Vector(c)).z for o in meshes for c in o.bound_box)
+ assert abs(z_min) < 0.002, f"lowest point z={z_min:.4f}: the object must stand on z=0"
+ print(f"[selfcheck] {len(meshes)} mesh objects, z_min={z_min:.4f}")
+
+'''
+
+
+def _constants(p: PartPlan) -> str:
+ mn, mx = p.bbox.min, p.bbox.max
+ pre = to_snake(p.name).upper()
+ return (
+ f"# ---- plan numbers (metres) for {to_pascal(p.name)} — keep the finished part inside this bbox\n"
+ f"{pre}_CENTER = {_fmt(p.bbox.center)}\n"
+ f"{pre}_EXTENTS = {_fmt(p.bbox.extents)}\n"
+ f"{pre}_MIN = {_fmt(mn)}\n"
+ f"{pre}_MAX = {_fmt(mx)}\n"
+ f"{pre}_INSTANCES = {p.instances}\n"
+ )
+
+
+def _part_function(p: PartPlan) -> str:
+ """``def build_<snake>() -> bpy.types.Object`` (placeholder box; instances looped inside)."""
+ pascal, snake, fn = to_pascal(p.name), to_snake(p.name), build_fn_name(p.name)
+ pre = snake.upper()
+ rgb, rough, metal = finish_for(f"{p.material} {p.description}")
+ mn, mx = p.bbox.min, p.bbox.max
+ lines = [
+ f"def {fn}():",
+ f' """{pascal} — {p.role}',
+ f" {p.description}",
+ f" Material: {p.material or 'n/a'}",
+ f" Plan bbox: center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}",
+ f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
+ ]
+ if p.attach_to:
+ lines.append(f" Attaches to: {to_pascal(p.attach_to)} (surfaces must touch, no gap)")
+ if p.instances > 1:
+ lines.append(f" Instances: {p.instances} ({p.symmetry}) -> named {pascal}_0..{pascal}_{p.instances - 1}, "
+ f"each TOP-LEVEL (no parent Empty — it would merge them into one measured part); returns the list")
+ lines += [' Returns the object(s) at WORLD pose (Z up, -Y front, metres).', ' """']
+ lines.append(f" mat = make_material(\"{pascal}Mat\", {_fmt(rgb)}, roughness={rough}, metallic={metal})")
+ if p.instances == 1:
+ lines += [
+ " # TODO: replace this placeholder box with the real geometry (keep the name + bbox)",
+ f" return add_box(\"{pascal}\", {pre}_CENTER, {pre}_EXTENTS, mat, bevel={_bevel(p.bbox):.4f})",
+ ]
+ else:
+ centers = [tuple(round(x, 4) for x in c) for c in instance_centers(p.bbox, p.instances, p.symmetry)]
+ lines += [
+ " objs = []",
+ f" for i, c in enumerate({centers}): # TODO: exact placement",
+ " # TODO: replace this placeholder box with the real geometry (keep the names + bbox)",
+ f" objs.append(add_box(f\"{pascal}_{{i}}\", c, {pre}_EXTENTS, mat, bevel={_bevel(p.bbox):.4f}))",
+ " return objs",
+ ]
+ return "\n".join(lines) + "\n"
+
+
+def _plan_header(plan: StaticPlan, *, multi_file: bool) -> str:
+ ob = plan.overall_bbox
+ parts_doc = "\n".join(
+ f" - {to_pascal(p.name)}{'' if p.instances == 1 else f' x{p.instances}'}: {p.role}; bbox center {_fmt(p.bbox.center)} "
+ f"extents {_fmt(p.bbox.extents)}" + (f" [{part_file_rel(p.name)}]" if multi_file else "")
+ for p in plan.parts
+ )
+ accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
+ layout = (
+ f" * LAYOUT: this file is the ENTRY. Each part lives in src/{PARTS_DIR}/<snake>.py and exports\n"
+ f" build_<snake>() -> bpy.types.Object; main() below imports and calls them in order.\n"
+ " Edit geometry in the part files; keep this file to imports + calls + self-check.\n"
+ if multi_file else
+ " * LAYOUT: single file (small object). One build_<snake>() per part, called from main().\n"
+ )
+ return f'''"""{plan.object_name} — Blender (bpy) model.
+
+{plan.summary}
+Style: {plan.style_notes or "n/a"}
+
+CONTRACT (the harness runs this file in an EMPTY scene with `blender -b --factory-startup`):
+ * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
+ * Overall bbox: center {_fmt(ob.center)} extents {_fmt(ob.extents)}
+ -> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
+ * One mesh object per part, named EXACTLY as below (PascalCase); instances Name_0..Name_N-1,
+ each TOP-LEVEL (never parented under an Empty — that merges them into ONE measured part).
+{layout} * Materials: Principled BSDF (Base Color / Roughness / Metallic). GLB keeps flat PBR + image
+ textures only (procedural node textures are NOT exported) — rely on geometry + flat PBR.
+ * Modifiers may stay unapplied (the exporter applies them). Keep < 500k triangles, < 120 s.
+ * NEVER: cameras, lights, world, render settings, export/import, file IO, bpy.ops.wm.*.
+ * Only bpy / bmesh / mathutils / math / random (seeded). No other imports.
+
+PARTS:
+{parts_doc}
+
+ACCEPTANCE:
+{accept}
+"""
+'''
+
+
+# ----------------------------------------------------------------------------- public renderers
+def part_file_source(p: PartPlan) -> str:
+ """Complete ``src/parts/<snake>.py`` text for one plan part (self-contained, runnable)."""
+ pascal, fn = to_pascal(p.name), build_fn_name(p.name)
+ doc = (
+ f'"""{pascal} — {p.role} (part module; imported by src/model.py).\n\n'
+ f"{p.description}\n"
+ f"Material: {p.material or 'n/a'}. Instances: {p.instances}"
+ + (f" ({p.symmetry})" if p.instances > 1 else "")
+ + (f". Attaches to: {to_pascal(p.attach_to)} (must touch, no gap)" if p.attach_to else "")
+ + f".\n\nExports `{fn}() -> bpy.types.Object`: builds the part at its WORLD pose (Z up, -Y front,\n"
+ "metres) with the exact object name(s) and returns it (list of TOP-LEVEL objects when\n"
+ "instanced — never parent instances under an Empty). Do NOT call it here — model.py does.\n"
+ "Keep this file self-contained (its own helpers); only bpy/bmesh/mathutils/math/random.\n"
+ '"""\n'
+ )
+ return doc + IMPORTS + "\n" + _constants(p) + HELPERS + "\n# ----------------------------------------------------------------------------- part\n" + _part_function(p)
+
+
+def model_file_source(plan: StaticPlan) -> str:
+ """Complete multi-file entry ``src/model.py``: imports, ordered calls, self-check."""
+ imports = "\n".join(f"from {PARTS_PKG}.{to_snake(p.name)} import {build_fn_name(p.name)}" for p in plan.parts)
+ calls = "\n".join(f" {build_fn_name(p.name)}()" for p in plan.parts)
+ return (
+ _plan_header(plan, multi_file=True)
+ + "import bpy\nfrom mathutils import Vector\n\n"
+ + imports + "\n\n"
+ + SELFCHECK
+ + "\ndef main():\n # build every part (order = plan order); parts are placed at world pose by their builders\n"
+ + calls + "\n _selfcheck()\n\n\nmain()\n"
+ )
+
+
+def blender_skeleton_source(plan: StaticPlan) -> str:
+ """The same model as ONE ``src/model.py`` (small objects may use a single file)."""
+ body = "\n# ----------------------------------------------------------------------------- parts\n"
+ for p in plan.parts:
+ body += _constants(p) + "\n\n" + _part_function(p) + "\n\n"
+ calls = "\n".join(f" {build_fn_name(p.name)}()" for p in plan.parts)
+ return (
+ _plan_header(plan, multi_file=False) + IMPORTS + HELPERS + body + SELFCHECK
+ + "\ndef main():\n" + calls + "\n _selfcheck()\n\n\nmain()\n"
+ )
+
+
+def write_blender_skeleton(ws: Workspace, plan: StaticPlan, *, multi_file: bool = True) -> list[Path]:
+ """Write the starter files (overwrites) and return the written paths (entry first)."""
+ ws.src.mkdir(parents=True, exist_ok=True)
+ entry = ws.src / "model.py"
+ if not multi_file:
+ entry.write_text(blender_skeleton_source(plan))
+ return [entry]
+ entry.write_text(model_file_source(plan))
+ written = [entry]
+ for p in plan.parts:
+ path = ws.root / part_file_rel(p.name)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(part_file_source(p))
+ written.append(path)
+ return written
+
+
+# ===================================================================== runtime
+# (merged from codeverse/languages/blender/runtime.py, 2026-08-28)
+_PKG_DIR = Path(__file__).resolve().parent
+WRAPPER = _PKG_DIR / "wrappers" / "run_bpy.py"
+
+
+class BlenderNotFoundError(RuntimeError):
+ """No usable Blender binary (configure ``CV3D_BINARIES__BLENDER`` or put blender on PATH)."""
+
+
+def blender_env() -> dict[str, str]:
+ """Environment for a headless Blender child: keep the user's env but make sure the
+ host python (conda) cannot leak into Blender's bundled interpreter, and strip
+ credential-shaped vars (:func:`codeverse.proc.scrub_secrets`) — the model-authored
+ ``model.py`` executes inside this process and must never see API keys."""
+ env = scrub_secrets(dict(os.environ))
+ for k in ("PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP"):
+ env.pop(k, None)
+ env["PYTHONNOUSERSITE"] = "1"
+ return env
+
+
+class BlenderRuntime:
+ """LanguageRuntime for ``Language.BLENDER``."""
+
+ language = Language.BLENDER
+ entry_globs: tuple[str, ...] = (ENTRY_REL, "src/parts/*.py")
+
+ def __init__(self, *, blender: str | None = None, settings: Settings | None = None):
+ self._settings = settings or get_settings()
+ self._blender = blender
+
+ # ------------------------------------------------------------------ helpers
+ 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 CV3D_BINARIES__BLENDER=/path/to/blender")
+ return b
+
+ def entry_file(self, ws: Workspace) -> Path:
+ return ws.root / ENTRY_REL
+
+ @staticmethod
+ def file_for_part(part_name: str) -> str:
+ """Workspace-relative file that owns a plan part: ``src/parts/<snake>.py``
+ (the tracks call this via ``getattr`` to fan out per-part refinement)."""
+ return part_file_rel(part_name)
+
+ def part_file(self, ws: Workspace, part_name: str) -> Path:
+ return ws.root / self.file_for_part(part_name)
+
+ @staticmethod
+ def file_for_target(target: str) -> list[str]:
+ """Refine target → files: whole-object targets (``overall``/``assembly``/``object``/'')
+ map to the entry ``src/model.py``; anything else is treated as a part name."""
+ if target.strip().lower() in ("", "overall", "assembly", "object", "model"):
+ return [ENTRY_REL]
+ return [part_file_rel(target)]
+
+ def build_command(
+ self, ws: Workspace, *, stl: bool = True, blend: bool = False, seed: int = 0,
+ tri_limit: int = MAX_TRIS_OBJECT, rlimit_gb: float | None = None,
+ ) -> list[str]:
+ cmd = [
+ self.blender_binary(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",
+ "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),
+ "--rlimit-gb", str(rlimit_gb if rlimit_gb is not None else self._settings.limits.bpy_rlimit_gb),
+ "--tri-limit", str(tri_limit), "--seed", str(seed),
+ ]
+ if stl:
+ cmd.append("--stl")
+ if blend:
+ cmd.append("--blend")
+ return cmd
+
+ # ------------------------------------------------------------------ protocol
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ if not isinstance(plan, StaticPlan): # ArticulatedPlan is a StaticPlan subclass → allowed
+ raise TypeError(f"BlenderRuntime.skeleton needs a StaticPlan/ArticulatedPlan, got {type(plan).__name__}")
+ return write_blender_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ """Lint every python file under ``src/`` + the multi-file layout rules."""
+ return lint_workspace(ws)
+
+ def build(
+ self, ws: Workspace, *, timeout_s: int | None = None, stl: bool = True, blend: bool = False,
+ seed: int = 0, tri_limit: int = MAX_TRIS_OBJECT,
+ ) -> BuildResult:
+ """Run the wrapper; never raises for agent-code failures (typed BuildResult instead)."""
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ build_json = ws.artifacts / "build.json"
+ census_json = ws.artifacts / "census.json"
+ glb = ws.artifacts / "object.glb"
+ stl_path = ws.artifacts / "object.stl"
+ blend_path = ws.artifacts / "object.blend"
+ # invalidate BEFORE the missing-entry early return: a deleted model.py must not
+ # leave the previous round's object.glb + build.json (ok: true) looking current
+ ws.stage_artifacts("build.json", "census.json", "object.glb", "object.stl", "object.blend").invalidate()
+ entry = self.entry_file(ws)
+ if not entry.is_file():
+ result = BuildResult(ok=False, language=self.language.value, error_type="MissingEntryFile",
+ error_message=f"{ENTRY_REL} does not exist", error_file=ENTRY_REL)
+ ws.write_json(build_json, result)
+ return result
+ cmd = self.build_command(ws, stl=stl, blend=blend, seed=seed, tri_limit=tri_limit)
+ proc = run_subprocess(
+ cmd, cwd=ws.root, env=blender_env(),
+ timeout_s=timeout_s or self._settings.limits.build_timeout_s,
+ )
+ return compose_build_result(
+ language=self.language.value, proc=proc, build_json=build_json, census_json=census_json,
+ glb_path=glb, extra_paths={"stl": stl_path, "blend": blend_path}, output_filter=strip_blender_noise,
+ )
+
+ def contract_doc(self) -> str:
+ p = PROMPTS_DIR / "blender" / "contract.md"
+ if p.is_file():
+ return p.read_text()
+ return (_PKG_DIR / "CONTRACT.md").read_text()
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "blender" / "cookbook.md"
diff --git a/harness/codeverse/languages/blender/layout.py b/harness/codeverse/languages/blender/layout.py
deleted file mode 100644
index 9077a338..00000000
--- a/harness/codeverse/languages/blender/layout.py
+++ /dev/null
@@ -1,154 +0,0 @@
-"""Multi-file layout of a blender workspace: ``src/model.py`` + ``src/parts/<snake>.py``.
-
-One place states the file convention so the runtime (``file_for_part``), the skeleton,
-the workspace lint and the prompts agree:
-
-* ``src/model.py`` — entry. Imports the part builders, calls them in order, runs the
- self-check. No geometry of its own beyond small glue.
-* ``src/parts/<snake>.py`` — one per plan part; exports ``def build_<snake>() -> bpy.types.Object``
- returning the named object at its world pose (instances ``Name_0..N-1`` built inside).
-* ``src/parts/_<anything>.py`` — optional shared helpers (not a part; no export required).
-* A single-file ``src/model.py`` (no ``parts/`` directory) stays valid for small objects.
-"""
-
-from __future__ import annotations
-
-import ast
-import time
-from pathlib import Path
-
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.contracts.common import ENTRY_FILE, Language
-from codeverse.conventions import to_snake
-from codeverse.languages.blender.lint import GATE, lint_blender_source
-from codeverse.workspace import Workspace
-
-ENTRY_REL = ENTRY_FILE[Language.BLENDER] # "src/model.py"
-PARTS_DIR = "parts"
-PARTS_PKG = "parts"
-
-
-def part_file_rel(part_name: str) -> str:
- """``'Seat Cushion'`` → ``'src/parts/seat_cushion.py'`` (workspace-relative)."""
- return f"src/{PARTS_DIR}/{to_snake(part_name)}.py"
-
-
-def build_fn_name(part_name: str) -> str:
- """``'SeatCushion'`` → ``'build_seat_cushion'`` (the function a part file must export)."""
- return f"build_{to_snake(part_name)}"
-
-
-def part_files(ws: Workspace) -> list[Path]:
- """Part modules present in the workspace (sorted; underscore helper modules excluded)."""
- d = ws.src / PARTS_DIR
- if not d.is_dir():
- return []
- return sorted(p for p in d.glob("*.py") if not p.name.startswith("_"))
-
-
-def helper_files(ws: Workspace) -> list[Path]:
- """Underscore-prefixed shared modules under ``src/parts/`` (linted, not required to export)."""
- d = ws.src / PARTS_DIR
- return sorted(d.glob("_*.py")) if d.is_dir() else []
-
-
-def source_files(ws: Workspace) -> list[Path]:
- """Every agent-authored python file under ``src/`` (entry first), including nested dirs."""
- entry = ws.src / "model.py"
- rest = sorted(p for p in ws.src.rglob("*.py") if p != entry)
- return ([entry] if entry.is_file() else []) + rest
-
-
-def _rel(ws: Workspace, p: Path) -> str:
- return p.relative_to(ws.root).as_posix()
-
-
-def _finding(sev: Severity, target: str, msg: str, hint: str, line: int | None = None) -> GateFinding:
- return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint,
- data={"line": line} if line else {})
-
-
-def _exported_functions(tree: ast.Module) -> set[str]:
- return {n.name for n in tree.body if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
-
-
-def _imported_part_modules(tree: ast.Module) -> set[str]:
- """snake names of ``parts.<snake>`` modules the entry references via import statements."""
- out: set[str] = set()
- for node in ast.walk(tree):
- if isinstance(node, ast.ImportFrom) and node.module:
- dotted = node.module.split(".")
- if dotted[0] == PARTS_PKG:
- if len(dotted) > 1:
- out.add(dotted[1])
- else: # ``from parts import seat, leg``
- out.update(a.name for a in node.names)
- elif isinstance(node, ast.Import):
- for a in node.names:
- dotted = a.name.split(".")
- if dotted[0] == PARTS_PKG and len(dotted) > 1:
- out.add(dotted[1])
- return out
-
-
-def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | None) -> list[GateFinding]:
- """Cross-file rules: naming, exported builders, import-time side effects, unused part files."""
- out: list[GateFinding] = []
- E, W = Severity.ERROR, Severity.WARN
- imported = _imported_part_modules(entry_tree) if entry_tree is not None else set()
- for p in parts:
- target = _rel(ws, p)
- stem = p.stem
- if stem != to_snake(stem):
- out.append(_finding(E, target, f"part file name '{p.name}' is not snake_case",
- f"rename to src/{PARTS_DIR}/{to_snake(stem)}.py (the harness maps plan part "
- f"'{stem}' → that file) and fix the import in model.py"))
- continue
- try:
- tree = ast.parse(p.read_text(), filename=target)
- except SyntaxError:
- continue # reported by the per-file lint
- fn = f"build_{stem}"
- if fn not in _exported_functions(tree):
- out.append(_finding(E, target, f"{target} does not define `def {fn}()`",
- f"every part file exports `def {fn}() -> bpy.types.Object` returning the named object "
- f"at its world pose; model.py calls it (`from {PARTS_PKG}.{stem} import {fn}`)"))
- for node in tree.body:
- if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
- name = getattr(node.value.func, "id", "")
- if name.startswith("build_") or name == "main":
- out.append(_finding(W, target, f"{target} calls `{name}()` at import time",
- "part files only DEFINE builders; model.py calls them once (a module-level "
- "call here builds the part twice → auto-suffixed 'Name.001')", node.lineno))
- if entry_tree is not None and stem not in imported:
- out.append(_finding(W, target, f"{target} is never imported by src/model.py → its part is not built",
- f"add `from {PARTS_PKG}.{stem} import {fn}` to model.py and call `{fn}()` in main()"))
- return out
-
-
-def lint_workspace(ws: Workspace) -> GateReport:
- """Lint every python file under ``src/`` + the multi-file layout rules (one merged report)."""
- t0 = time.monotonic()
- entry = ws.src / "model.py"
- if not entry.is_file():
- return GateReport(gate=GATE, passed=False, duration_ms=0, findings=[_finding(
- Severity.ERROR, ENTRY_REL, f"{ENTRY_REL} is missing",
- "create src/model.py (entry: imports src/parts/<snake>.py builders and calls them; see the skeleton)")])
- parts = part_files(ws)
- findings: list[GateFinding] = []
- for p in source_files(ws):
- target = _rel(ws, p)
- is_entry = p == entry
- is_helper = p.name.startswith("_")
- rep = lint_blender_source(p.read_text(), target=target,
- expect_names=not (is_helper or (is_entry and bool(parts))),
- expect_bpy=not is_helper)
- findings.extend(rep.findings)
- entry_tree: ast.Module | None
- try:
- entry_tree = ast.parse(entry.read_text(), filename=ENTRY_REL)
- except SyntaxError:
- entry_tree = None
- findings.extend(_layout_rules(ws, parts, entry_tree))
- passed = not any(f.severity == Severity.ERROR for f in findings)
- return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
diff --git a/harness/codeverse/languages/blender/lint.py b/harness/codeverse/languages/blender/lint.py
deleted file mode 100644
index 340ce89e..00000000
--- a/harness/codeverse/languages/blender/lint.py
+++ /dev/null
@@ -1,300 +0,0 @@
-"""Static lint for agent-authored bpy scripts (``src/model.py`` and ``src/parts/*.py``).
-
-AST based, offline, milliseconds. Catches what the build would only reveal
-after a 2-10 s Blender round-trip — and the contract violations the build
-cannot see (file IO, render calls). Findings carry a concrete ``fix_hint``.
-
-Severity policy: ERROR = will fail at runtime or violates the contract;
-WARN = fragile in headless Blender / likely wrong; INFO = advice.
-"""
-
-from __future__ import annotations
-
-import ast
-import re
-import time
-from pathlib import Path
-
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.languages._ast_lint import ( # noqa: F401 — dotted re-exported
- BASE_FORBIDDEN_IMPORTS,
- check_imports,
- describe_parse_failure,
- dotted,
- safe_parse,
-)
-
-GATE = "lint:blender"
-
-ALLOWED_IMPORTS = {
- "bpy", "bmesh", "mathutils", "math", "random", "numpy", "np", "itertools", "functools",
- "collections", "typing", "dataclasses", "colorsys", "statistics", "operator", "enum", "copy",
- # os/sys are deliberately ALLOWED here (unlike cadquery/opengl): headless bpy scripts
- # touch them legitimately and the forbidden-call rules below catch the harmful uses.
- "sys", "os", "__future__", "bpy_extras",
- "parts", # the workspace's own src/parts/<snake>.py modules (multi-file layout)
-}
-FORBIDDEN_IMPORTS = frozenset(BASE_FORBIDDEN_IMPORTS | {"pathlib"})
-# dotted-name prefixes of calls that violate the contract (harness owns them)
-FORBIDDEN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
- ("bpy.ops.render.", "rendering is done by the harness; delete all bpy.ops.render.* calls"),
- ("bpy.ops.export_", "export is done by the harness; delete all bpy.ops.export_* calls"),
- ("bpy.ops.import_", "no imports of external files; build geometry procedurally"),
- ("bpy.ops.wm.", "no bpy.ops.wm.* (file open/save/append/link/quit); the harness owns the file"),
- ("bpy.ops.image.save", "no image file writes"),
- ("bpy.data.libraries.", "no linking/appending external .blend data"),
- ("os.system", "no shell commands"),
- ("os.remove", "no file IO"), ("os.unlink", "no file IO"), ("os.rmdir", "no file IO"),
- ("os.makedirs", "no file IO"), ("os.mkdir", "no file IO"), ("os.rename", "no file IO"),
- ("subprocess.", "no subprocesses"),
- ("urllib.", "no network"), ("requests.", "no network"),
- ("shutil.", "no file IO"),
-)
-WARN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
- ("bpy.data.cameras.new", "the harness owns cameras; remove camera creation"),
- ("bpy.ops.object.camera_add", "the harness owns cameras; remove camera creation"),
- ("bpy.data.lights.new", "the harness owns lighting; remove light creation"),
- ("bpy.ops.object.light_add", "the harness owns lighting; remove light creation"),
- ("bpy.data.worlds.new", "the harness owns the world/background; remove world code"),
- ("bpy.ops.view3d.", "view3d operators fail in background mode (no 3D viewport)"),
- ("bpy.ops.screen.", "screen operators fail in background mode"),
- ("sys.exit", "do not exit; let the script fall off the end"),
-)
-# Principled BSDF inputs that raise KeyError in Blender 4.x/5.x → their replacement.
-# Verified against Blender 5.0.1: 'Anisotropic' and 'Specular Tint' STILL EXIST (do not list them).
-REMOVED_BSDF_INPUTS = {
- "Specular": "Specular IOR Level", "Subsurface": "Subsurface Weight", "Transmission": "Transmission Weight",
- "Emission": "Emission Color (+ 'Emission Strength')", "Subsurface Color": "Base Color (subsurface tint removed)",
- "Clearcoat": "Coat Weight", "Clearcoat Roughness": "Coat Roughness", "Sheen": "Sheen Weight",
- "Transmission Roughness": "(removed) use Roughness",
-}
-KNOWN_BINDINGS = ("Vector", "Matrix", "Euler", "Quaternion", "bmesh", "math", "random", "np", "numpy", "bpy")
-PASCAL_RE = re.compile(r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*(?:_\d+)?$")
-
-
-class _Collector(ast.NodeVisitor):
- """One pass over the tree; rules read the collected facts."""
-
- def __init__(self) -> None:
- self.imports: dict[str, int] = {} # top-level module → line
- self.bound: set[str] = set()
- self.calls: list[tuple[str, ast.Call]] = []
- self.attr_stores: list[tuple[str, int]] = [] # dotted target of assignments
- self.name_loads: list[tuple[str, int]] = []
- self.bm_names: set[str] = set() # names bound from bmesh.new() / bmesh.from_edit_mesh()
- self.bm_subscripts: list[tuple[str, int]] = [] # (base name, line) of <name>.verts/edges/faces[i]
- self.bsdf_inputs: list[tuple[str, int]] = []
- self.names_assigned: list[str] = [] # string constants assigned to .name / name=
- self.constants: list[tuple[str, int]] = []
- self.has_temp_override = False
- self.keywords: list[tuple[str, int]] = []
-
- def visit_Import(self, node: ast.Import) -> None:
- for a in node.names:
- top = a.name.split(".")[0]
- self.imports.setdefault(top, node.lineno)
- self.bound.add((a.asname or a.name).split(".")[0])
-
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
- top = (node.module or "").split(".")[0]
- self.imports.setdefault(top, node.lineno)
- for a in node.names:
- self.bound.add(a.asname or a.name)
-
- def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
- self.bound.add(node.name)
- for a in node.args.args + node.args.kwonlyargs + node.args.posonlyargs:
- self.bound.add(a.arg)
- if node.args.vararg:
- self.bound.add(node.args.vararg.arg)
- if node.args.kwarg:
- self.bound.add(node.args.kwarg.arg)
- self.generic_visit(node)
-
- visit_AsyncFunctionDef = visit_FunctionDef # type: ignore[assignment]
-
- def visit_ClassDef(self, node: ast.ClassDef) -> None:
- self.bound.add(node.name)
- self.generic_visit(node)
-
- def visit_Name(self, node: ast.Name) -> None:
- if isinstance(node.ctx, ast.Load):
- self.name_loads.append((node.id, node.lineno))
- else:
- self.bound.add(node.id)
-
- def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
- if node.name:
- self.bound.add(node.name)
- self.generic_visit(node)
-
- def visit_Call(self, node: ast.Call) -> None:
- name = dotted(node.func)
- self.calls.append((name, node))
- if name.endswith("temp_override"):
- self.has_temp_override = True
- for a in node.args:
- if isinstance(a, ast.Constant) and isinstance(a.value, str):
- self.names_assigned.append(a.value)
- for kw in node.keywords:
- if kw.arg:
- self.keywords.append((kw.arg, node.lineno))
- if kw.arg == "name" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
- self.names_assigned.append(kw.value.value)
- self.generic_visit(node)
-
- def visit_Assign(self, node: ast.Assign) -> None:
- for t in node.targets:
- d = dotted(t)
- if d:
- self.attr_stores.append((d, node.lineno))
- v = node.value
- if isinstance(v, ast.Call) and dotted(v.func) in ("bmesh.new", "bmesh.from_edit_mesh"):
- self.bm_names.update(t.id for t in node.targets if isinstance(t, ast.Name))
- if isinstance(v, ast.Constant) and isinstance(v.value, str):
- self.names_assigned.append(v.value)
- elif isinstance(v, ast.JoinedStr) and v.values and isinstance(v.values[0], ast.Constant):
- self.names_assigned.append(str(v.values[0].value).rstrip("_"))
- self.generic_visit(node)
-
- def visit_Subscript(self, node: ast.Subscript) -> None:
- if isinstance(node.value, ast.Attribute):
- # only <Name>.verts/edges/faces[i] — e.verts[0] (BMEdge) / me.edges[i] (Mesh) are
- # filtered later against the names actually bound to a bmesh (BMElemSeq).
- if (node.value.attr in ("verts", "edges", "faces") and not isinstance(node.slice, ast.Slice)
- and isinstance(node.value.value, ast.Name)):
- self.bm_subscripts.append((node.value.value.id, node.lineno))
- if node.value.attr == "inputs" and isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, str):
- self.bsdf_inputs.append((node.slice.value, node.lineno))
- self.generic_visit(node)
-
- def visit_Constant(self, node: ast.Constant) -> None:
- if isinstance(node.value, str):
- self.constants.append((node.value, node.lineno))
-
-
-def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target: str = "src/model.py") -> GateFinding:
- data = {"line": line} if line else {}
- 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]:
- 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(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(E, f"forbidden import `{mod}`", line, "only bpy/bmesh/mathutils/math/random/numpy (+stdlib data helpers) are allowed")
- return _f(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(E, f"forbidden call `{name}`", call.lineno, hint))
- for prefix, hint in WARN_CALL_PREFIXES:
- if name.startswith(prefix):
- out.append(_f(W, f"`{name}` — {hint}", call.lineno, hint))
- if name == "open":
- out.append(_f(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(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(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(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(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)`"))
- if name.endswith("bpy.ops.object.join") or name == "bpy.ops.object.join":
- out.append(_f(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(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(E, "Mesh.calc_normals() was removed in 4.0 (normals are computed automatically)", call.lineno, "delete the call (use me.update() if needed)"))
- if name == "bpy.ops.wm.redraw_timer":
- pass
- for target, line in c.attr_stores:
- if target.endswith(".use_auto_smooth") or target.endswith(".auto_smooth_angle"):
- out.append(_f(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(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(W, f"`{target}` assignment — cameras/world are owned by the harness", line, "remove camera/world code"))
- if target.endswith(".use_nodes"):
- out.append(_f(I, "`use_nodes = True` is a no-op in Blender 5.x (materials always have a node tree); harmless", line, ""))
- for key, line in c.bsdf_inputs:
- if key in REMOVED_BSDF_INPUTS:
- out.append(_f(E, f"Principled BSDF input '{key}' does not exist in Blender 4.x/5.x (KeyError at runtime)", line,
- f"use inputs['{REMOVED_BSDF_INPUTS[key]}']"))
- elif key == "Specular Tint":
- out.append(_f(I, "'Specular Tint' is an RGBA colour in Blender 4.x/5.x (a float raises TypeError)", line,
- 'assign a 4-tuple: inputs["Specular Tint"].default_value = (r, g, b, 1.0)'))
- has_lookup = any(n.endswith("ensure_lookup_table") for n, _ in c.calls)
- # only subscripts on a BMESH object need ensure_lookup_table (BMElemSeq); e.verts[0]
- # (BMEdge/BMFace tuples) and me.edges[i] (Mesh collections) are always fine.
- bm_subs = [line for base, line in c.bm_subscripts if base in c.bm_names or base == "bm"]
- if "bmesh" in c.imports and bm_subs and not has_lookup:
- out.append(_f(E, "bmesh verts/edges/faces indexed with [] but ensure_lookup_table() is never called → IndexError", bm_subs[0],
- "after bm.from_mesh()/any topology change call `bm.verts.ensure_lookup_table(); bm.edges.ensure_lookup_table(); bm.faces.ensure_lookup_table()` before indexing"))
- for name, line in c.name_loads:
- if name in KNOWN_BINDINGS and name not in c.bound:
- hint = {"Vector": "from mathutils import Vector", "Matrix": "from mathutils import Matrix", "Euler": "from mathutils import Euler",
- "Quaternion": "from mathutils import Quaternion", "np": "import numpy as np", "numpy": "import numpy"}.get(name, f"import {name}")
- out.append(_f(E, f"`{name}` is used but never imported (NameError at runtime)", line, hint))
- break
- if "bpy.context.selected_objects" in source:
- out.append(_f(W, "bpy.context.selected_objects is unreliable in background mode (often empty)", None,
- "keep references to the objects you create (`obj = bpy.context.object` right after primitive_*_add) instead of re-reading the selection"))
- for const, line in c.constants:
- if const == "BLENDER_EEVEE_NEXT":
- out.append(_f(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"))
- 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(I, f"named objects: {sorted(set(pascal))[:12]}", None, ""))
- elif expect_names:
- out.append(_f(W, "no PascalCase object names found (e.g. obj.name = 'SeatCushion')", None,
- "name every visible mesh after its part: `obj.name = 'SeatCushion'`; instances `Leg_0..Leg_3`"))
- return out
-
-
-def lint_blender_source(
- source: str, *, target: str = "src/model.py", expect_names: bool = True, expect_bpy: bool = True,
-) -> GateReport:
- """Lint one bpy script; returns ``GateReport(gate='lint:blender')``.
-
- ``expect_names=False`` silences the PascalCase-name warning (multi-file entry files
- only import and call builders); ``expect_bpy=False`` allows helper modules that do
- not touch bpy. :func:`codeverse.languages.blender.layout.lint_workspace` lints a
- whole ``src/`` tree with these set per file.
- """
- t0 = time.monotonic()
- findings: list[GateFinding] = []
- tree, exc = safe_parse(source, target)
- if tree is None:
- msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
- findings.append(_f(Severity.ERROR, msg, line, hint, target))
- return GateReport(gate=GATE, passed=False, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
- c = _Collector()
- c.visit(tree)
- findings = _rules(c, source, target=target, expect_names=expect_names, expect_bpy=expect_bpy)
- for f in findings:
- f.target = target
- passed = not any(f.severity == Severity.ERROR for f in findings)
- return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
-
-
-def lint_blender_file(path: Path, *, target: str = "src/model.py") -> GateReport:
- if not path.is_file():
- return GateReport(gate=GATE, passed=False, findings=[_f(Severity.ERROR, f"{target} is missing", None, "create src/model.py (see the skeleton)", target)])
- return lint_blender_source(path.read_text(), target=target)
diff --git a/harness/codeverse/languages/blender/runtime.py b/harness/codeverse/languages/blender/runtime.py
deleted file mode 100644
index e68c29a2..00000000
--- a/harness/codeverse/languages/blender/runtime.py
+++ /dev/null
@@ -1,152 +0,0 @@
-"""BlenderRuntime: lint → build (headless Blender subprocess) → BuildResult.
-
-Layout (see ``layout.py``): ``src/model.py`` is the entry; ``src/parts/<snake>.py`` hold
-one ``build_<snake>()`` per plan part (``file_for_part`` maps a part to its file so the
-tracks can refine parts in parallel); a single-file ``model.py`` stays valid. The
-agent's code is never imported here; ``wrappers/run_bpy.py`` runs it inside Blender
-(with ``src/`` on ``sys.path``), writes ``artifacts/build.json`` + ``census.json`` and
-exports ``artifacts/object.glb`` (Y-up, +Z front) and ``object.stl`` (Z-up).
-"""
-
-from __future__ import annotations
-
-import os
-from pathlib import Path
-
-from codeverse.config import Settings, get_settings
-from codeverse.contracts.artifacts import BuildResult, GateReport
-from codeverse.contracts.common import Language
-from codeverse.contracts.plan import Plan, StaticPlan
-from codeverse.conventions import MAX_TRIS_OBJECT
-from codeverse.languages._common import (
- compose_build_result,
- run_subprocess,
- strip_blender_noise,
-)
-from codeverse.languages.blender.layout import ENTRY_REL, lint_workspace, part_file_rel
-from codeverse.languages.blender.skeleton import write_blender_skeleton
-from codeverse.proc import scrub_secrets
-from codeverse.prompts import PROMPTS_DIR
-from codeverse.workspace import Workspace
-
-_PKG_DIR = Path(__file__).resolve().parent
-WRAPPER = _PKG_DIR / "wrappers" / "run_bpy.py"
-
-
-class BlenderNotFoundError(RuntimeError):
- """No usable Blender binary (configure ``CV3D_BINARIES__BLENDER`` or put blender on PATH)."""
-
-
-def blender_env() -> dict[str, str]:
- """Environment for a headless Blender child: keep the user's env but make sure the
- host python (conda) cannot leak into Blender's bundled interpreter, and strip
- credential-shaped vars (:func:`codeverse.proc.scrub_secrets`) — the model-authored
- ``model.py`` executes inside this process and must never see API keys."""
- env = scrub_secrets(dict(os.environ))
- for k in ("PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP"):
- env.pop(k, None)
- env["PYTHONNOUSERSITE"] = "1"
- return env
-
-
-class BlenderRuntime:
- """LanguageRuntime for ``Language.BLENDER``."""
-
- language = Language.BLENDER
- entry_globs: tuple[str, ...] = (ENTRY_REL, "src/parts/*.py")
-
- def __init__(self, *, blender: str | None = None, settings: Settings | None = None):
- self._settings = settings or get_settings()
- self._blender = blender
-
- # ------------------------------------------------------------------ helpers
- 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 CV3D_BINARIES__BLENDER=/path/to/blender")
- return b
-
- def entry_file(self, ws: Workspace) -> Path:
- return ws.root / ENTRY_REL
-
- @staticmethod
- def file_for_part(part_name: str) -> str:
- """Workspace-relative file that owns a plan part: ``src/parts/<snake>.py``
- (the tracks call this via ``getattr`` to fan out per-part refinement)."""
- return part_file_rel(part_name)
-
- def part_file(self, ws: Workspace, part_name: str) -> Path:
- return ws.root / self.file_for_part(part_name)
-
- @staticmethod
- def file_for_target(target: str) -> list[str]:
- """Refine target → files: whole-object targets (``overall``/``assembly``/``object``/'')
- map to the entry ``src/model.py``; anything else is treated as a part name."""
- if target.strip().lower() in ("", "overall", "assembly", "object", "model"):
- return [ENTRY_REL]
- return [part_file_rel(target)]
-
- def build_command(
- self, ws: Workspace, *, stl: bool = True, blend: bool = False, seed: int = 0,
- tri_limit: int = MAX_TRIS_OBJECT, rlimit_gb: float | None = None,
- ) -> list[str]:
- cmd = [
- self.blender_binary(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",
- "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),
- "--rlimit-gb", str(rlimit_gb if rlimit_gb is not None else self._settings.limits.bpy_rlimit_gb),
- "--tri-limit", str(tri_limit), "--seed", str(seed),
- ]
- if stl:
- cmd.append("--stl")
- if blend:
- cmd.append("--blend")
- return cmd
-
- # ------------------------------------------------------------------ protocol
- def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
- if not isinstance(plan, StaticPlan): # ArticulatedPlan is a StaticPlan subclass → allowed
- raise TypeError(f"BlenderRuntime.skeleton needs a StaticPlan/ArticulatedPlan, got {type(plan).__name__}")
- return write_blender_skeleton(ws, plan)
-
- def lint(self, ws: Workspace) -> GateReport:
- """Lint every python file under ``src/`` + the multi-file layout rules."""
- return lint_workspace(ws)
-
- def build(
- self, ws: Workspace, *, timeout_s: int | None = None, stl: bool = True, blend: bool = False,
- seed: int = 0, tri_limit: int = MAX_TRIS_OBJECT,
- ) -> BuildResult:
- """Run the wrapper; never raises for agent-code failures (typed BuildResult instead)."""
- ws.artifacts.mkdir(parents=True, exist_ok=True)
- build_json = ws.artifacts / "build.json"
- census_json = ws.artifacts / "census.json"
- glb = ws.artifacts / "object.glb"
- stl_path = ws.artifacts / "object.stl"
- blend_path = ws.artifacts / "object.blend"
- # invalidate BEFORE the missing-entry early return: a deleted model.py must not
- # leave the previous round's object.glb + build.json (ok: true) looking current
- ws.stage_artifacts("build.json", "census.json", "object.glb", "object.stl", "object.blend").invalidate()
- entry = self.entry_file(ws)
- if not entry.is_file():
- result = BuildResult(ok=False, language=self.language.value, error_type="MissingEntryFile",
- error_message=f"{ENTRY_REL} does not exist", error_file=ENTRY_REL)
- ws.write_json(build_json, result)
- return result
- cmd = self.build_command(ws, stl=stl, blend=blend, seed=seed, tri_limit=tri_limit)
- proc = run_subprocess(
- cmd, cwd=ws.root, env=blender_env(),
- timeout_s=timeout_s or self._settings.limits.build_timeout_s,
- )
- return compose_build_result(
- language=self.language.value, proc=proc, build_json=build_json, census_json=census_json,
- glb_path=glb, extra_paths={"stl": stl_path, "blend": blend_path}, output_filter=strip_blender_noise,
- )
-
- def contract_doc(self) -> str:
- p = PROMPTS_DIR / "blender" / "contract.md"
- if p.is_file():
- return p.read_text()
- return (_PKG_DIR / "CONTRACT.md").read_text()
-
- def cookbook_path(self) -> Path:
- return PROMPTS_DIR / "blender" / "cookbook.md"
diff --git a/harness/codeverse/languages/blender/skeleton.py b/harness/codeverse/languages/blender/skeleton.py
deleted file mode 100644
index ce691ae7..00000000
--- a/harness/codeverse/languages/blender/skeleton.py
+++ /dev/null
@@ -1,288 +0,0 @@
-"""Starter files for the blender language, generated from a plan.
-
-Default layout (multi-file, refinable part-by-part in parallel):
-
-* ``src/parts/<snake>.py`` — one per plan part. Self-contained (own tiny helpers),
- plan numbers as constants on top, description/role/material/attach_to in the
- docstring, and ``def build_<snake>() -> bpy.types.Object`` that builds a placeholder
- box at the plan bbox (instances ``Name_0..N-1`` as TOP-LEVEL objects — never under a
- parent Empty: the harness measures top-level GLB nodes as parts, and an Empty parent
- would merge all instances into one part).
-* ``src/model.py`` — entry: imports the builders, calls them in order, self-checks.
-
-``blender_skeleton_source(plan)`` still renders the same model as ONE file (small
-objects may use a single ``src/model.py``). Both layouts build as written: the agent
-starts from a passing build and replaces placeholder bodies one function at a time.
-Only raw bpy in the output — no harness imports.
-"""
-
-from __future__ import annotations
-
-import math
-from pathlib import Path
-
-from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
-from codeverse.conventions import to_pascal, to_snake
-from codeverse.languages.blender.layout import PARTS_DIR, PARTS_PKG, build_fn_name, part_file_rel
-from codeverse.workspace import Workspace
-
-# keyword → (rgb, roughness, metallic) placeholder finishes so the first render is not all-grey
-_FINISHES: tuple[tuple[tuple[str, ...], tuple[float, float, float], float, float], ...] = (
- (("wood", "oak", "walnut", "pine", "timber", "birch"), (0.55, 0.36, 0.20), 0.55, 0.0),
- (("steel", "chrome", "aluminium", "aluminum", "metal", "iron", "brass"), (0.75, 0.75, 0.78), 0.35, 1.0),
- (("fabric", "cloth", "cushion", "upholster", "velvet", "linen"), (0.45, 0.30, 0.30), 0.9, 0.0),
- (("leather",), (0.30, 0.16, 0.10), 0.6, 0.0),
- (("glass", "acrylic"), (0.85, 0.9, 0.95), 0.05, 0.0),
- (("rubber", "tire", "tyre"), (0.05, 0.05, 0.05), 0.9, 0.0),
- (("plastic", "abs", "nylon"), (0.9, 0.9, 0.9), 0.4, 0.0),
- (("black",), (0.05, 0.05, 0.05), 0.5, 0.0),
- (("white",), (0.9, 0.9, 0.9), 0.5, 0.0),
- (("red",), (0.7, 0.1, 0.1), 0.5, 0.0),
- (("blue",), (0.1, 0.2, 0.7), 0.5, 0.0),
- (("green",), (0.1, 0.5, 0.2), 0.5, 0.0),
-)
-
-
-def finish_for(text: str) -> tuple[tuple[float, float, float], float, float]:
- """Placeholder (rgb, roughness, metallic) from material words; neutral grey otherwise."""
- low = text.lower()
- for words, rgb, rough, metal in _FINISHES:
- if any(w in low for w in words):
- return rgb, rough, metal
- return (0.6, 0.6, 0.6), 0.5, 0.0
-
-
-def instance_centers(bbox: BBox, n: int, symmetry: str) -> list[tuple[float, float, float]]:
- """Placeholder centres for ``n`` instances of a part using the plan's symmetry hint."""
- cx, cy, cz = bbox.center
- if n <= 1:
- return [(cx, cy, cz)]
- if n == 2 and symmetry == "mirror_x":
- return [(abs(cx), cy, cz), (-abs(cx), cy, cz)]
- if n == 2 and symmetry == "mirror_y":
- return [(cx, abs(cy), cz), (cx, -abs(cy), cz)]
- if n == 4 and symmetry in ("mirror_x", "mirror_y"):
- ax, ay = abs(cx), abs(cy)
- return [(ax, -ay, cz), (-ax, -ay, cz), (-ax, ay, cz), (ax, ay, cz)]
- if symmetry == "radial":
- r = math.hypot(cx, cy)
- a0 = math.atan2(cy, cx)
- return [(r * math.cos(a0 + 2 * math.pi * i / n), r * math.sin(a0 + 2 * math.pi * i / n), cz) for i in range(n)]
- return [(cx, cy, cz) for _ in range(n)]
-
-
-def _fmt(v: tuple[float, float, float]) -> str:
- return "(" + ", ".join(f"{x:.3f}" for x in v) + ")"
-
-
-def _bevel(bbox: BBox) -> float:
- return max(0.0, min(0.01, 0.08 * min(bbox.extents)))
-
-
-# ----------------------------------------------------------------------------- shared text blocks
-IMPORTS = '''import math
-import random
-
-import bpy
-import bmesh # noqa: F401 (available for custom meshes: bm = bmesh.new(); ... bm.to_mesh(me))
-from mathutils import Vector, Matrix # noqa: F401
-
-random.seed(0)
-'''
-
-HELPERS = '''
-# ----------------------------------------------------------------------------- helpers (plain bpy)
-def make_material(name, rgb, roughness=0.5, metallic=0.0):
- """Principled BSDF material with flat PBR values (what the GLB keeps)."""
- 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 add_box(name, center, extents, material=None, bevel=0.0):
- """Axis-aligned box: size=1 cube scaled to `extents`, scale baked into the mesh."""
- bpy.ops.mesh.primitive_cube_add(size=1, location=center, scale=extents)
- obj = bpy.context.object
- obj.name = name
- bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
- if material is not None:
- obj.data.materials.append(material)
- if bevel > 0:
- mod = obj.modifiers.new("Bevel", "BEVEL")
- mod.width = bevel
- mod.segments = 3
- mod.limit_method = "ANGLE"
- return obj
-
-'''
-
-SELFCHECK = '''
-def _selfcheck():
- """What the harness checks first: meshes exist, no auto-suffixed names, stands on z=0."""
- bpy.context.view_layer.update()
- meshes = [o for o in bpy.data.objects if o.type == "MESH"]
- assert meshes, "no mesh objects built"
- for o in meshes:
- assert "." not in o.name, f"auto-suffixed name {o.name!r}: give every instance its own name"
- z_min = min((o.matrix_world @ Vector(c)).z for o in meshes for c in o.bound_box)
- assert abs(z_min) < 0.002, f"lowest point z={z_min:.4f}: the object must stand on z=0"
- print(f"[selfcheck] {len(meshes)} mesh objects, z_min={z_min:.4f}")
-
-'''
-
-
-def _constants(p: PartPlan) -> str:
- mn, mx = p.bbox.min, p.bbox.max
- pre = to_snake(p.name).upper()
- return (
- f"# ---- plan numbers (metres) for {to_pascal(p.name)} — keep the finished part inside this bbox\n"
- f"{pre}_CENTER = {_fmt(p.bbox.center)}\n"
- f"{pre}_EXTENTS = {_fmt(p.bbox.extents)}\n"
- f"{pre}_MIN = {_fmt(mn)}\n"
- f"{pre}_MAX = {_fmt(mx)}\n"
- f"{pre}_INSTANCES = {p.instances}\n"
- )
-
-
-def _part_function(p: PartPlan) -> str:
- """``def build_<snake>() -> bpy.types.Object`` (placeholder box; instances looped inside)."""
- pascal, snake, fn = to_pascal(p.name), to_snake(p.name), build_fn_name(p.name)
- pre = snake.upper()
- rgb, rough, metal = finish_for(f"{p.material} {p.description}")
- mn, mx = p.bbox.min, p.bbox.max
- lines = [
- f"def {fn}():",
- f' """{pascal} — {p.role}',
- f" {p.description}",
- f" Material: {p.material or 'n/a'}",
- f" Plan bbox: center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}",
- f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
- ]
- if p.attach_to:
- lines.append(f" Attaches to: {to_pascal(p.attach_to)} (surfaces must touch, no gap)")
- if p.instances > 1:
- lines.append(f" Instances: {p.instances} ({p.symmetry}) -> named {pascal}_0..{pascal}_{p.instances - 1}, "
- f"each TOP-LEVEL (no parent Empty — it would merge them into one measured part); returns the list")
- lines += [' Returns the object(s) at WORLD pose (Z up, -Y front, metres).', ' """']
- lines.append(f" mat = make_material(\"{pascal}Mat\", {_fmt(rgb)}, roughness={rough}, metallic={metal})")
- if p.instances == 1:
- lines += [
- " # TODO: replace this placeholder box with the real geometry (keep the name + bbox)",
- f" return add_box(\"{pascal}\", {pre}_CENTER, {pre}_EXTENTS, mat, bevel={_bevel(p.bbox):.4f})",
- ]
- else:
- centers = [tuple(round(x, 4) for x in c) for c in instance_centers(p.bbox, p.instances, p.symmetry)]
- lines += [
- " objs = []",
- f" for i, c in enumerate({centers}): # TODO: exact placement",
- " # TODO: replace this placeholder box with the real geometry (keep the names + bbox)",
- f" objs.append(add_box(f\"{pascal}_{{i}}\", c, {pre}_EXTENTS, mat, bevel={_bevel(p.bbox):.4f}))",
- " return objs",
- ]
- return "\n".join(lines) + "\n"
-
-
-def _plan_header(plan: StaticPlan, *, multi_file: bool) -> str:
- ob = plan.overall_bbox
- parts_doc = "\n".join(
- f" - {to_pascal(p.name)}{'' if p.instances == 1 else f' x{p.instances}'}: {p.role}; bbox center {_fmt(p.bbox.center)} "
- f"extents {_fmt(p.bbox.extents)}" + (f" [{part_file_rel(p.name)}]" if multi_file else "")
- for p in plan.parts
- )
- accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
- layout = (
- f" * LAYOUT: this file is the ENTRY. Each part lives in src/{PARTS_DIR}/<snake>.py and exports\n"
- f" build_<snake>() -> bpy.types.Object; main() below imports and calls them in order.\n"
- " Edit geometry in the part files; keep this file to imports + calls + self-check.\n"
- if multi_file else
- " * LAYOUT: single file (small object). One build_<snake>() per part, called from main().\n"
- )
- return f'''"""{plan.object_name} — Blender (bpy) model.
-
-{plan.summary}
-Style: {plan.style_notes or "n/a"}
-
-CONTRACT (the harness runs this file in an EMPTY scene with `blender -b --factory-startup`):
- * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
- * Overall bbox: center {_fmt(ob.center)} extents {_fmt(ob.extents)}
- -> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
- * One mesh object per part, named EXACTLY as below (PascalCase); instances Name_0..Name_N-1,
- each TOP-LEVEL (never parented under an Empty — that merges them into ONE measured part).
-{layout} * Materials: Principled BSDF (Base Color / Roughness / Metallic). GLB keeps flat PBR + image
- textures only (procedural node textures are NOT exported) — rely on geometry + flat PBR.
- * Modifiers may stay unapplied (the exporter applies them). Keep < 500k triangles, < 120 s.
- * NEVER: cameras, lights, world, render settings, export/import, file IO, bpy.ops.wm.*.
- * Only bpy / bmesh / mathutils / math / random (seeded). No other imports.
-
-PARTS:
-{parts_doc}
-
-ACCEPTANCE:
-{accept}
-"""
-'''
-
-
-# ----------------------------------------------------------------------------- public renderers
-def part_file_source(p: PartPlan) -> str:
- """Complete ``src/parts/<snake>.py`` text for one plan part (self-contained, runnable)."""
- pascal, fn = to_pascal(p.name), build_fn_name(p.name)
- doc = (
- f'"""{pascal} — {p.role} (part module; imported by src/model.py).\n\n'
- f"{p.description}\n"
- f"Material: {p.material or 'n/a'}. Instances: {p.instances}"
- + (f" ({p.symmetry})" if p.instances > 1 else "")
- + (f". Attaches to: {to_pascal(p.attach_to)} (must touch, no gap)" if p.attach_to else "")
- + f".\n\nExports `{fn}() -> bpy.types.Object`: builds the part at its WORLD pose (Z up, -Y front,\n"
- "metres) with the exact object name(s) and returns it (list of TOP-LEVEL objects when\n"
- "instanced — never parent instances under an Empty). Do NOT call it here — model.py does.\n"
- "Keep this file self-contained (its own helpers); only bpy/bmesh/mathutils/math/random.\n"
- '"""\n'
- )
- return doc + IMPORTS + "\n" + _constants(p) + HELPERS + "\n# ----------------------------------------------------------------------------- part\n" + _part_function(p)
-
-
-def model_file_source(plan: StaticPlan) -> str:
- """Complete multi-file entry ``src/model.py``: imports, ordered calls, self-check."""
- imports = "\n".join(f"from {PARTS_PKG}.{to_snake(p.name)} import {build_fn_name(p.name)}" for p in plan.parts)
- calls = "\n".join(f" {build_fn_name(p.name)}()" for p in plan.parts)
- return (
- _plan_header(plan, multi_file=True)
- + "import bpy\nfrom mathutils import Vector\n\n"
- + imports + "\n\n"
- + SELFCHECK
- + "\ndef main():\n # build every part (order = plan order); parts are placed at world pose by their builders\n"
- + calls + "\n _selfcheck()\n\n\nmain()\n"
- )
-
-
-def blender_skeleton_source(plan: StaticPlan) -> str:
- """The same model as ONE ``src/model.py`` (small objects may use a single file)."""
- body = "\n# ----------------------------------------------------------------------------- parts\n"
- for p in plan.parts:
- body += _constants(p) + "\n\n" + _part_function(p) + "\n\n"
- calls = "\n".join(f" {build_fn_name(p.name)}()" for p in plan.parts)
- return (
- _plan_header(plan, multi_file=False) + IMPORTS + HELPERS + body + SELFCHECK
- + "\ndef main():\n" + calls + "\n _selfcheck()\n\n\nmain()\n"
- )
-
-
-def write_blender_skeleton(ws: Workspace, plan: StaticPlan, *, multi_file: bool = True) -> list[Path]:
- """Write the starter files (overwrites) and return the written paths (entry first)."""
- ws.src.mkdir(parents=True, exist_ok=True)
- entry = ws.src / "model.py"
- if not multi_file:
- entry.write_text(blender_skeleton_source(plan))
- return [entry]
- entry.write_text(model_file_source(plan))
- written = [entry]
- for p in plan.parts:
- path = ws.root / part_file_rel(p.name)
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(part_file_source(p))
- written.append(path)
- return written
diff --git a/harness/codeverse/languages/cadquery/__init__.py b/harness/codeverse/languages/cadquery/__init__.py
index f56796bf..66f90e9f 100644
--- a/harness/codeverse/languages/cadquery/__init__.py
+++ b/harness/codeverse/languages/cadquery/__init__.py
@@ -1,13 +1,395 @@
"""CadQuery language: runtime, lint, skeleton; wrapper runs in a python subprocess."""
-from codeverse.languages.cadquery.lint import lint_cadquery_file, lint_cadquery_source
-from codeverse.languages.cadquery.runtime import CadQueryRuntime
-from codeverse.languages.cadquery.skeleton import cadquery_skeleton_source, write_cadquery_skeleton
-
-__all__ = [
- "CadQueryRuntime",
- "cadquery_skeleton_source",
- "lint_cadquery_file",
- "lint_cadquery_source",
- "write_cadquery_skeleton",
-]
+from __future__ import annotations
+
+import ast
+import os
+import re
+import sys
+import time
+from pathlib import Path
+
+from codeverse.config import Settings, get_settings
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.plan import PartPlan, Plan, StaticPlan
+from codeverse.conventions import MAX_TRIS_OBJECT, to_pascal, to_snake
+from codeverse.languages._ast_lint import ( # noqa: F401 — dotted re-exported
+ BASE_FORBIDDEN_IMPORTS,
+ check_imports,
+ describe_parse_failure,
+ dotted,
+ safe_parse,
+)
+from codeverse.languages._common import compose_build_result, run_subprocess
+from codeverse.languages.blender import finish_for, instance_centers
+from codeverse.proc import scrub_secrets
+from codeverse.prompts import PROMPTS_DIR
+from codeverse.workspace import Workspace
+
+# ===================================================================== lint
+# (merged from codeverse/languages/cadquery/lint.py, 2026-08-28)
+GATE = "lint:cadquery"
+ALLOWED_IMPORTS = {"cadquery", "cq", "math", "random", "numpy", "np", "itertools", "functools", "collections",
+ "typing", "dataclasses", "enum", "copy", "statistics", "operator", "__future__"}
+FORBIDDEN_IMPORTS = frozenset(BASE_FORBIDDEN_IMPORTS | {
+ "os", "sys", "pathlib", # no file-system / interpreter access (unlike blender, nothing legitimate needs them)
+ "OCP", "OCC", "ocp_vscode", "cq_editor", "cq_warehouse", "build123d", # raw cadquery only — no OCC/tooling layers
+})
+FORBIDDEN_CALLS: tuple[tuple[str, str], ...] = (
+ ("show_object", "show_object() exists only in CQ-editor; delete it — the harness renders for you"),
+ ("show", "show() is for notebooks/CQ-editor; delete it"),
+ ("open", "no file IO; the harness exports STEP/STL/GLB from `result`"),
+ ("cq.exporters.export", "no exporting; assign the model to `result` and the harness exports"),
+ ("exporters.export", "no exporting; assign the model to `result` and the harness exports"),
+ ("cq.importers.", "no importing external geometry; build it procedurally"),
+ ("importers.", "no importing external geometry; build it procedurally"),
+ ("exit", "never exit; `result` must be readable after the module runs"),
+ ("quit", "never exit"),
+)
+FORBIDDEN_METHODS = {"save": "no .save()/.export() on the assembly — the harness exports", "export": "no .export() — the harness exports",
+ "exportStep": "no export calls", "exportStl": "no export calls", "exportSvg": "no export calls"}
+PASCAL_RE = re.compile(r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*(?:_\d+)?$")
+
+
+RADIAN_CONSTS = {"pi", "tau"}
+TO_RADIANS_FUNCS = {"radians", "deg2rad"}
+TO_DEGREES_FUNCS = {"degrees", "rad2deg"}
+
+
+def looks_like_radians(expr: ast.expr) -> bool:
+ """True when ``expr`` is a radians expression (``math.pi``, ``math.pi / 2``, ``i * 2 * math.pi / n``,
+ ``math.radians(a)``) — never a plain name/number, never a conversion TO degrees
+ (``a * 180 / math.pi``, ``math.degrees(a)``). Only the ``pi``/``tau`` constants and the
+ radians/degrees helpers are inspected, so identifiers such as ``n_pins`` or ``pitch`` cannot match.
+ """
+ hit = False
+
+ def walk(node: ast.AST, inverted: bool) -> bool:
+ """Return True to stop: the expression is a conversion to degrees."""
+ nonlocal hit
+ if isinstance(node, ast.Call):
+ fn = dotted(node.func).rsplit(".", 1)[-1]
+ if fn in TO_DEGREES_FUNCS:
+ return True
+ if fn in TO_RADIANS_FUNCS:
+ hit = True
+ return any(walk(a, inverted) for a in node.args)
+ if isinstance(node, ast.BinOp):
+ if walk(node.left, inverted):
+ return True
+ return walk(node.right, inverted != isinstance(node.op, ast.Div))
+ is_const = (isinstance(node, ast.Attribute) and node.attr in RADIAN_CONSTS) or (isinstance(node, ast.Name) and node.id in RADIAN_CONSTS)
+ if is_const:
+ if inverted: # ``x * 180 / math.pi`` → degrees
+ return True
+ hit = True
+ return False
+ return any(walk(ch, inverted) for ch in ast.iter_child_nodes(node))
+
+ if walk(expr, False):
+ return False
+ return hit
+
+
+def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target: str = "src/model.py") -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data={"line": line} if line else {})
+
+
+class _Collector(ast.NodeVisitor):
+ def __init__(self) -> None:
+ self.imports: dict[str, int] = {}
+ self.calls: list[tuple[str, ast.Call]] = []
+ self.add_calls: list[ast.Call] = []
+ self.name_kw: list[str] = []
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ top = a.name.split(".")[0]
+ self.imports.setdefault(top, node.lineno)
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ self.imports.setdefault((node.module or "").split(".")[0], node.lineno)
+
+ def visit_Call(self, node: ast.Call) -> None:
+ name = dotted(node.func)
+ self.calls.append((name, node))
+ if name.endswith(".add"):
+ self.add_calls.append(node)
+ for kw in node.keywords:
+ if kw.arg == "name" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
+ self.name_kw.append(kw.value.value)
+ self.generic_visit(node)
+
+
+def _top_level_assigned(tree: ast.Module) -> tuple[set[str], set[str]]:
+ """Names bound at module level; names bound only under ``if __name__ == '__main__'``."""
+ top: set[str] = set()
+ guarded: set[str] = set()
+
+ def targets(stmt: ast.stmt) -> list[str]:
+ out = []
+ if isinstance(stmt, (ast.Assign,)):
+ for t in stmt.targets:
+ out += [n.id for n in ast.walk(t) if isinstance(n, ast.Name)]
+ elif isinstance(stmt, (ast.AnnAssign, ast.AugAssign)) and isinstance(stmt.target, ast.Name):
+ out.append(stmt.target.id)
+ elif isinstance(stmt, (ast.For, ast.With, ast.If, ast.Try)):
+ for sub in ast.iter_child_nodes(stmt):
+ if isinstance(sub, ast.stmt):
+ out += targets(sub)
+ return out
+
+ for stmt in tree.body:
+ if isinstance(stmt, ast.If) and "__main__" in ast.dump(stmt.test):
+ for sub in stmt.body:
+ guarded.update(targets(sub))
+ else:
+ top.update(targets(stmt))
+ return top, guarded
+
+
+def _rules(c: _Collector, 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:
+ out.append(_f(E, "model.py never imports cadquery", 1, "start with `import cadquery as cq`"))
+
+ def _import_finding(kind: str, mod: str, line: int) -> GateFinding:
+ if kind == "forbidden":
+ return _f(E, f"forbidden import `{mod}`", line, "only `cadquery`, `math`, `random`, `numpy` (+ stdlib data helpers) are allowed")
+ return _f(W, f"unexpected import `{mod}` (may not exist in the build sandbox)", line, "stick to cadquery / math / random / numpy")
+
+ out.extend(check_imports(c.imports, forbidden=FORBIDDEN_IMPORTS, allowed=ALLOWED_IMPORTS, make_finding=_import_finding))
+ top, guarded = _top_level_assigned(tree)
+ if "result" not in top:
+ hint = "assign `result = cq.Assembly(...)` (or a Workplane) at module level, NOT under `if __name__ == '__main__':`" if "result" in guarded \
+ else "end the file with a module-level `result = <cq.Assembly or cq.Workplane>`"
+ out.append(_f(E, "no module-level `result` assignment", None, hint))
+ for name, call in c.calls:
+ for pat, hint in FORBIDDEN_CALLS:
+ if name == pat or (pat.endswith(".") and name.startswith(pat)):
+ out.append(_f(E, f"forbidden call `{name}()`", call.lineno, hint))
+ last = name.rsplit(".", 1)[-1] if "." in name else ""
+ if last in FORBIDDEN_METHODS and not name.startswith("cq."):
+ out.append(_f(E, f"forbidden call `{name}()`", call.lineno, FORBIDDEN_METHODS[last]))
+ if name.endswith("Solid.makeSphere") and not any(k.arg and k.arg.startswith("angle") for k in call.keywords):
+ out.append(_f(W, "cq.Solid.makeSphere(r) without angle args builds a partial sphere in some versions", call.lineno,
+ "use `cq.Workplane('XY').sphere(r)` or pass angleDegrees1=-90, angleDegrees2=90, angleDegrees3=360"))
+ if name.endswith(".rotate") and len(call.args) == 3 and looks_like_radians(call.args[2]):
+ out.append(_f(E, ".rotate(...) takes DEGREES; this argument looks like radians (math.pi expression)", call.lineno,
+ "pass degrees: `.rotate((0,0,0), (0,0,1), 90)` or `math.degrees(angle_rad)`"))
+ if name.endswith(".fillet") or name.endswith(".chamfer"):
+ out.append(_f(I, f"{last}: OCC fails ('BRep_API: command not done') when radius >= wall thickness or edges conflict", call.lineno,
+ "keep radius < 0.45 x min thickness; select few edges (`.edges('|Z')`); wrap cosmetic fillets in try/except"))
+ if c.add_calls:
+ unnamed = [a.lineno for a in c.add_calls if not any(k.arg == "name" for k in a.keywords)]
+ if unnamed:
+ out.append(_f(W, f"assembly .add() without name= at line(s) {unnamed[:6]} → auto uuid node names", unnamed[0],
+ "give every part a PascalCase name: `.add(shape, name='SeatCushion', color=cq.Color(r, g, b))`"))
+ uncol = [a.lineno for a in c.add_calls if not any(k.arg == "color" for k in a.keywords)]
+ if uncol:
+ out.append(_f(I, f".add() without color= at line(s) {uncol[:6]} (exports grey)", uncol[0], "add `color=cq.Color(r, g, b)` (0-1 floats)"))
+ bad = [n for n in c.name_kw if not PASCAL_RE.match(n)]
+ if bad:
+ out.append(_f(W, f"part names not PascalCase: {bad[:6]}", None, "use PascalCase part names, instances Name_0..Name_N"))
+ elif "Assembly" not in source:
+ out.append(_f(W, "result is not a cq.Assembly: the model exports as ONE unnamed part", None,
+ "prefer `result = cq.Assembly(); result.add(part, name='PartName', color=cq.Color(...))` per part"))
+ if re.search(r"\.cylinder\(\s*[0-9.]+\s*,\s*[0-9.]+\s*\)", source):
+ out.append(_f(I, "Workplane.cylinder(height, radius): height comes FIRST", None, "check the argument order: .cylinder(height, radius)"))
+ return out
+
+
+def lint_cadquery_source(source: str, *, target: str = "src/model.py") -> GateReport:
+ t0 = time.monotonic()
+ tree, exc = safe_parse(source, target)
+ if tree is None:
+ msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
+ f = _f(Severity.ERROR, msg, line, hint, target)
+ return GateReport(gate=GATE, passed=False, findings=[f], duration_ms=int((time.monotonic() - t0) * 1000))
+ c = _Collector()
+ c.visit(tree)
+ findings = _rules(c, tree, source)
+ for f in findings:
+ f.target = target
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
+
+
+def lint_cadquery_file(path: Path, *, target: str = "src/model.py") -> GateReport:
+ if not path.is_file():
+ return GateReport(gate=GATE, passed=False, findings=[_f(Severity.ERROR, f"{target} is missing", None, "create src/model.py (see the skeleton)", target)])
+ return lint_cadquery_source(path.read_text(), target=target)
+
+
+# ===================================================================== skeleton
+# (merged from codeverse/languages/cadquery/skeleton.py, 2026-08-28)
+def _fmt(v: tuple[float, float, float]) -> str:
+ return "(" + ", ".join(f"{x:.3f}" for x in v) + ")"
+
+
+def _part_function(p: PartPlan) -> str:
+ pascal, snake = to_pascal(p.name), to_snake(p.name)
+ mn, mx = p.bbox.min, p.bbox.max
+ ex, ey, ez = p.bbox.extents
+ lines = [
+ f"def build_{snake}():",
+ f' """{pascal} — {p.role}',
+ f" {p.description}",
+ f" Material: {p.material or 'n/a'}",
+ f" Plan bbox (world, Z-up): center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}",
+ f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
+ ]
+ if p.attach_to:
+ lines.append(f" Attaches to: {to_pascal(p.attach_to)} (faces must touch; small overlaps are fine)")
+ if p.instances > 1:
+ lines.append(f" Instances: {p.instances} ({p.symmetry}); build ONE centred at the origin, main() places each copy.")
+ lines.append(' """')
+ lines.append(" # TODO: replace the placeholder box (keep it centred on the origin; placement happens in main())")
+ lines.append(f" return cq.Workplane(\"XY\").box({ex:.3f}, {ey:.3f}, {ez:.3f})")
+ else:
+ lines.append(' """')
+ lines.append(" # TODO: replace the placeholder box with the real geometry (keep the name + bbox)")
+ lines.append(f" return cq.Workplane(\"XY\").box({ex:.3f}, {ey:.3f}, {ez:.3f}).translate({_fmt(p.bbox.center)})")
+ lines += ["", ""]
+ return "\n".join(lines)
+
+
+def _main_body(plan: StaticPlan) -> str:
+ lines = [f'result = cq.Assembly(name="{to_pascal(plan.object_name)}")', ""]
+ for p in plan.parts:
+ pascal, snake = to_pascal(p.name), to_snake(p.name)
+ rgb, _r, _m = finish_for(f"{p.material} {p.description}")
+ color = f"cq.Color({rgb[0]:.2f}, {rgb[1]:.2f}, {rgb[2]:.2f})"
+ if p.instances == 1:
+ lines.append(f'result.add(build_{snake}(), name="{pascal}", color={color})')
+ continue
+ centers = instance_centers(p.bbox, p.instances, p.symmetry)
+ lines.append(f"_{snake} = build_{snake}()")
+ lines.append(f"for _i, _c in enumerate({[tuple(round(x, 4) for x in c) for c in centers]}): # TODO: exact placement")
+ lines.append(f' result.add(_{snake}, name=f"{pascal}_{{_i}}", loc=cq.Location(cq.Vector(*_c)), color={color})')
+ lines.append("")
+ return "\n".join(lines)
+
+
+def cadquery_skeleton_source(plan: StaticPlan) -> str:
+ """Return the complete starter ``model.py`` text for ``plan``."""
+ ob = plan.overall_bbox
+ parts_doc = "\n".join(
+ f" - {to_pascal(p.name)}{'' if p.instances == 1 else f' x{p.instances}'}: {p.role}; bbox center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}"
+ for p in plan.parts
+ )
+ accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
+ header = f'''"""{plan.object_name} — CadQuery model.
+
+{plan.summary}
+Style: {plan.style_notes or "n/a"}
+
+CONTRACT (the harness imports this file and exports `result` to GLB/STEP/STL itself):
+ * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
+ * Overall bbox: center {_fmt(ob.center)} extents {_fmt(ob.extents)}
+ -> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
+ * `result` = cq.Assembly; one `.add(shape, name="PascalName", color=cq.Color(r, g, b))` per part,
+ instances Name_0..Name_N-1 (a shape built at the origin + `loc=cq.Location(cq.Vector(x, y, z))`).
+ * Only `import cadquery as cq` (+ math / random). No file IO, no export, no show_object.
+ * `.box(x, y, z)` is centred; `.cylinder(height, radius)`; `.rotate(p1, p2, DEGREES)`;
+ `.translate()/.rotate()` return NEW objects (reassign). Keep fillet radius < 0.45 x wall thickness.
+
+PARTS:
+{parts_doc}
+
+ACCEPTANCE:
+{accept}
+"""
+import math # noqa: F401
+
+import cadquery as cq
+
+
+'''
+ body = "".join(_part_function(p) for p in plan.parts)
+ return header + body + _main_body(plan)
+
+
+def write_cadquery_skeleton(ws: Workspace, plan: StaticPlan) -> list[Path]:
+ ws.src.mkdir(parents=True, exist_ok=True)
+ path = ws.src / "model.py"
+ path.write_text(cadquery_skeleton_source(plan))
+ return [path]
+
+
+# ===================================================================== runtime
+# (merged from codeverse/languages/cadquery/runtime.py, 2026-08-28)
+_PKG_DIR = Path(__file__).resolve().parent
+WRAPPER = _PKG_DIR / "wrappers" / "run_cq.py"
+
+
+def cadquery_env() -> dict[str, str]:
+ """Environment for the wrapper subprocess that executes the model-authored
+ ``src/model.py``: the user's env minus credential-shaped vars
+ (:func:`codeverse.proc.scrub_secrets`)."""
+ env = scrub_secrets(dict(os.environ))
+ env.pop("PYTHONSTARTUP", None)
+ env.setdefault("OMP_NUM_THREADS", "4")
+ env.setdefault("PYTHONUNBUFFERED", "1")
+ return env
+
+
+class CadQueryRuntime:
+ """LanguageRuntime for ``Language.CADQUERY``."""
+
+ language = Language.CADQUERY
+ entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.CADQUERY],)
+
+ def __init__(self, *, python: str | None = None, settings: Settings | None = None, rlimit_gb: float = 8.0):
+ self._settings = settings or get_settings()
+ self._python = python or sys.executable
+ self._rlimit_gb = rlimit_gb
+
+ def entry_file(self, ws: Workspace) -> Path:
+ return ws.src / "model.py"
+
+ def build_command(self, ws: Workspace, *, seed: int = 0, tri_limit: int = MAX_TRIS_OBJECT,
+ tolerance: float = 0.001, angular_tolerance: float = 0.15) -> list[str]:
+ return [
+ self._python, str(WRAPPER), "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),
+ "--rlimit-gb", str(self._rlimit_gb), "--tri-limit", str(tri_limit), "--seed", str(seed),
+ "--tolerance", str(tolerance), "--angular-tolerance", str(angular_tolerance),
+ ]
+
+ # ------------------------------------------------------------------ protocol
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ if not isinstance(plan, StaticPlan):
+ raise TypeError(f"CadQueryRuntime.skeleton needs a StaticPlan, got {type(plan).__name__}")
+ return write_cadquery_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_cadquery_file(self.entry_file(ws))
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None, seed: int = 0,
+ tri_limit: int = MAX_TRIS_OBJECT) -> BuildResult:
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ build_json, census_json = ws.artifacts / "build.json", ws.artifacts / "census.json"
+ glb, step, stl = ws.artifacts / "object.glb", ws.artifacts / "object.step", ws.artifacts / "object.stl"
+ # invalidate BEFORE the missing-entry early return (same reasoning as BlenderRuntime.build)
+ ws.stage_artifacts("build.json", "census.json", "object.glb", "object.step", "object.stl").invalidate()
+ entry = self.entry_file(ws)
+ if not entry.is_file():
+ result = BuildResult(ok=False, language=self.language.value, error_type="MissingEntryFile",
+ error_message="src/model.py does not exist", error_file="src/model.py")
+ ws.write_json(build_json, result)
+ return result
+ proc = run_subprocess(self.build_command(ws, seed=seed, tri_limit=tri_limit), cwd=ws.root, env=cadquery_env(),
+ timeout_s=timeout_s or self._settings.limits.build_timeout_s)
+ return compose_build_result(language=self.language.value, proc=proc, build_json=build_json, census_json=census_json,
+ glb_path=glb, extra_paths={"step": step, "stl": stl})
+
+ def contract_doc(self) -> str:
+ p = PROMPTS_DIR / "cadquery" / "contract.md"
+ if p.is_file():
+ return p.read_text()
+ return (_PKG_DIR / "CONTRACT.md").read_text()
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "cadquery" / "cookbook.md"
diff --git a/harness/codeverse/languages/cadquery/lint.py b/harness/codeverse/languages/cadquery/lint.py
deleted file mode 100644
index a4d6a494..00000000
--- a/harness/codeverse/languages/cadquery/lint.py
+++ /dev/null
@@ -1,215 +0,0 @@
-"""Static lint for agent-authored CadQuery scripts (``src/model.py``).
-
-AST based, offline. Enforces the import allow-list, forbids file IO / export /
-``show_object``, requires a module-level ``result`` and flags the known OCC
-pitfalls (degree/radian confusion, hemisphere ``makeSphere``, unnamed parts …).
-"""
-
-from __future__ import annotations
-
-import ast
-import re
-import time
-from pathlib import Path
-
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.languages._ast_lint import ( # noqa: F401 — dotted re-exported
- BASE_FORBIDDEN_IMPORTS,
- check_imports,
- describe_parse_failure,
- dotted,
- safe_parse,
-)
-
-GATE = "lint:cadquery"
-ALLOWED_IMPORTS = {"cadquery", "cq", "math", "random", "numpy", "np", "itertools", "functools", "collections",
- "typing", "dataclasses", "enum", "copy", "statistics", "operator", "__future__"}
-FORBIDDEN_IMPORTS = frozenset(BASE_FORBIDDEN_IMPORTS | {
- "os", "sys", "pathlib", # no file-system / interpreter access (unlike blender, nothing legitimate needs them)
- "OCP", "OCC", "ocp_vscode", "cq_editor", "cq_warehouse", "build123d", # raw cadquery only — no OCC/tooling layers
-})
-FORBIDDEN_CALLS: tuple[tuple[str, str], ...] = (
- ("show_object", "show_object() exists only in CQ-editor; delete it — the harness renders for you"),
- ("show", "show() is for notebooks/CQ-editor; delete it"),
- ("open", "no file IO; the harness exports STEP/STL/GLB from `result`"),
- ("cq.exporters.export", "no exporting; assign the model to `result` and the harness exports"),
- ("exporters.export", "no exporting; assign the model to `result` and the harness exports"),
- ("cq.importers.", "no importing external geometry; build it procedurally"),
- ("importers.", "no importing external geometry; build it procedurally"),
- ("exit", "never exit; `result` must be readable after the module runs"),
- ("quit", "never exit"),
-)
-FORBIDDEN_METHODS = {"save": "no .save()/.export() on the assembly — the harness exports", "export": "no .export() — the harness exports",
- "exportStep": "no export calls", "exportStl": "no export calls", "exportSvg": "no export calls"}
-PASCAL_RE = re.compile(r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*(?:_\d+)?$")
-
-
-RADIAN_CONSTS = {"pi", "tau"}
-TO_RADIANS_FUNCS = {"radians", "deg2rad"}
-TO_DEGREES_FUNCS = {"degrees", "rad2deg"}
-
-
-def looks_like_radians(expr: ast.expr) -> bool:
- """True when ``expr`` is a radians expression (``math.pi``, ``math.pi / 2``, ``i * 2 * math.pi / n``,
- ``math.radians(a)``) — never a plain name/number, never a conversion TO degrees
- (``a * 180 / math.pi``, ``math.degrees(a)``). Only the ``pi``/``tau`` constants and the
- radians/degrees helpers are inspected, so identifiers such as ``n_pins`` or ``pitch`` cannot match.
- """
- hit = False
-
- def walk(node: ast.AST, inverted: bool) -> bool:
- """Return True to stop: the expression is a conversion to degrees."""
- nonlocal hit
- if isinstance(node, ast.Call):
- fn = dotted(node.func).rsplit(".", 1)[-1]
- if fn in TO_DEGREES_FUNCS:
- return True
- if fn in TO_RADIANS_FUNCS:
- hit = True
- return any(walk(a, inverted) for a in node.args)
- if isinstance(node, ast.BinOp):
- if walk(node.left, inverted):
- return True
- return walk(node.right, inverted != isinstance(node.op, ast.Div))
- is_const = (isinstance(node, ast.Attribute) and node.attr in RADIAN_CONSTS) or (isinstance(node, ast.Name) and node.id in RADIAN_CONSTS)
- if is_const:
- if inverted: # ``x * 180 / math.pi`` → degrees
- return True
- hit = True
- return False
- return any(walk(ch, inverted) for ch in ast.iter_child_nodes(node))
-
- if walk(expr, False):
- return False
- return hit
-
-
-def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target: str = "src/model.py") -> GateFinding:
- return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data={"line": line} if line else {})
-
-
-class _Collector(ast.NodeVisitor):
- def __init__(self) -> None:
- self.imports: dict[str, int] = {}
- self.calls: list[tuple[str, ast.Call]] = []
- self.add_calls: list[ast.Call] = []
- self.name_kw: list[str] = []
-
- def visit_Import(self, node: ast.Import) -> None:
- for a in node.names:
- top = a.name.split(".")[0]
- self.imports.setdefault(top, node.lineno)
-
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
- self.imports.setdefault((node.module or "").split(".")[0], node.lineno)
-
- def visit_Call(self, node: ast.Call) -> None:
- name = dotted(node.func)
- self.calls.append((name, node))
- if name.endswith(".add"):
- self.add_calls.append(node)
- for kw in node.keywords:
- if kw.arg == "name" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
- self.name_kw.append(kw.value.value)
- self.generic_visit(node)
-
-
-def _top_level_assigned(tree: ast.Module) -> tuple[set[str], set[str]]:
- """Names bound at module level; names bound only under ``if __name__ == '__main__'``."""
- top: set[str] = set()
- guarded: set[str] = set()
-
- def targets(stmt: ast.stmt) -> list[str]:
- out = []
- if isinstance(stmt, (ast.Assign,)):
- for t in stmt.targets:
- out += [n.id for n in ast.walk(t) if isinstance(n, ast.Name)]
- elif isinstance(stmt, (ast.AnnAssign, ast.AugAssign)) and isinstance(stmt.target, ast.Name):
- out.append(stmt.target.id)
- elif isinstance(stmt, (ast.For, ast.With, ast.If, ast.Try)):
- for sub in ast.iter_child_nodes(stmt):
- if isinstance(sub, ast.stmt):
- out += targets(sub)
- return out
-
- for stmt in tree.body:
- if isinstance(stmt, ast.If) and "__main__" in ast.dump(stmt.test):
- for sub in stmt.body:
- guarded.update(targets(sub))
- else:
- top.update(targets(stmt))
- return top, guarded
-
-
-def _rules(c: _Collector, 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:
- out.append(_f(E, "model.py never imports cadquery", 1, "start with `import cadquery as cq`"))
-
- def _import_finding(kind: str, mod: str, line: int) -> GateFinding:
- if kind == "forbidden":
- return _f(E, f"forbidden import `{mod}`", line, "only `cadquery`, `math`, `random`, `numpy` (+ stdlib data helpers) are allowed")
- return _f(W, f"unexpected import `{mod}` (may not exist in the build sandbox)", line, "stick to cadquery / math / random / numpy")
-
- out.extend(check_imports(c.imports, forbidden=FORBIDDEN_IMPORTS, allowed=ALLOWED_IMPORTS, make_finding=_import_finding))
- top, guarded = _top_level_assigned(tree)
- if "result" not in top:
- hint = "assign `result = cq.Assembly(...)` (or a Workplane) at module level, NOT under `if __name__ == '__main__':`" if "result" in guarded \
- else "end the file with a module-level `result = <cq.Assembly or cq.Workplane>`"
- out.append(_f(E, "no module-level `result` assignment", None, hint))
- for name, call in c.calls:
- for pat, hint in FORBIDDEN_CALLS:
- if name == pat or (pat.endswith(".") and name.startswith(pat)):
- out.append(_f(E, f"forbidden call `{name}()`", call.lineno, hint))
- last = name.rsplit(".", 1)[-1] if "." in name else ""
- if last in FORBIDDEN_METHODS and not name.startswith("cq."):
- out.append(_f(E, f"forbidden call `{name}()`", call.lineno, FORBIDDEN_METHODS[last]))
- if name.endswith("Solid.makeSphere") and not any(k.arg and k.arg.startswith("angle") for k in call.keywords):
- out.append(_f(W, "cq.Solid.makeSphere(r) without angle args builds a partial sphere in some versions", call.lineno,
- "use `cq.Workplane('XY').sphere(r)` or pass angleDegrees1=-90, angleDegrees2=90, angleDegrees3=360"))
- if name.endswith(".rotate") and len(call.args) == 3 and looks_like_radians(call.args[2]):
- out.append(_f(E, ".rotate(...) takes DEGREES; this argument looks like radians (math.pi expression)", call.lineno,
- "pass degrees: `.rotate((0,0,0), (0,0,1), 90)` or `math.degrees(angle_rad)`"))
- if name.endswith(".fillet") or name.endswith(".chamfer"):
- out.append(_f(I, f"{last}: OCC fails ('BRep_API: command not done') when radius >= wall thickness or edges conflict", call.lineno,
- "keep radius < 0.45 x min thickness; select few edges (`.edges('|Z')`); wrap cosmetic fillets in try/except"))
- if c.add_calls:
- unnamed = [a.lineno for a in c.add_calls if not any(k.arg == "name" for k in a.keywords)]
- if unnamed:
- out.append(_f(W, f"assembly .add() without name= at line(s) {unnamed[:6]} → auto uuid node names", unnamed[0],
- "give every part a PascalCase name: `.add(shape, name='SeatCushion', color=cq.Color(r, g, b))`"))
- uncol = [a.lineno for a in c.add_calls if not any(k.arg == "color" for k in a.keywords)]
- if uncol:
- out.append(_f(I, f".add() without color= at line(s) {uncol[:6]} (exports grey)", uncol[0], "add `color=cq.Color(r, g, b)` (0-1 floats)"))
- bad = [n for n in c.name_kw if not PASCAL_RE.match(n)]
- if bad:
- out.append(_f(W, f"part names not PascalCase: {bad[:6]}", None, "use PascalCase part names, instances Name_0..Name_N"))
- elif "Assembly" not in source:
- out.append(_f(W, "result is not a cq.Assembly: the model exports as ONE unnamed part", None,
- "prefer `result = cq.Assembly(); result.add(part, name='PartName', color=cq.Color(...))` per part"))
- if re.search(r"\.cylinder\(\s*[0-9.]+\s*,\s*[0-9.]+\s*\)", source):
- out.append(_f(I, "Workplane.cylinder(height, radius): height comes FIRST", None, "check the argument order: .cylinder(height, radius)"))
- return out
-
-
-def lint_cadquery_source(source: str, *, target: str = "src/model.py") -> GateReport:
- t0 = time.monotonic()
- tree, exc = safe_parse(source, target)
- if tree is None:
- msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
- f = _f(Severity.ERROR, msg, line, hint, target)
- return GateReport(gate=GATE, passed=False, findings=[f], duration_ms=int((time.monotonic() - t0) * 1000))
- c = _Collector()
- c.visit(tree)
- findings = _rules(c, tree, source)
- for f in findings:
- f.target = target
- passed = not any(f.severity == Severity.ERROR for f in findings)
- return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
-
-
-def lint_cadquery_file(path: Path, *, target: str = "src/model.py") -> GateReport:
- if not path.is_file():
- return GateReport(gate=GATE, passed=False, findings=[_f(Severity.ERROR, f"{target} is missing", None, "create src/model.py (see the skeleton)", target)])
- return lint_cadquery_source(path.read_text(), target=target)
diff --git a/harness/codeverse/languages/cadquery/runtime.py b/harness/codeverse/languages/cadquery/runtime.py
deleted file mode 100644
index 59428740..00000000
--- a/harness/codeverse/languages/cadquery/runtime.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""CadQueryRuntime: lint → build (python subprocess running ``wrappers/run_cq.py``) → BuildResult.
-
-The wrapper needs ``cadquery`` + ``trimesh`` importable by the interpreter it runs
-under (``sys.executable`` by default; override with ``python`` for a dedicated env).
-"""
-
-from __future__ import annotations
-
-import os
-import sys
-from pathlib import Path
-
-from codeverse.config import Settings, get_settings
-from codeverse.contracts.artifacts import BuildResult, GateReport
-from codeverse.contracts.common import ENTRY_FILE, Language
-from codeverse.contracts.plan import Plan, StaticPlan
-from codeverse.conventions import MAX_TRIS_OBJECT
-from codeverse.languages._common import compose_build_result, run_subprocess
-from codeverse.languages.cadquery.lint import lint_cadquery_file
-from codeverse.languages.cadquery.skeleton import write_cadquery_skeleton
-from codeverse.proc import scrub_secrets
-from codeverse.prompts import PROMPTS_DIR
-from codeverse.workspace import Workspace
-
-_PKG_DIR = Path(__file__).resolve().parent
-WRAPPER = _PKG_DIR / "wrappers" / "run_cq.py"
-
-
-def cadquery_env() -> dict[str, str]:
- """Environment for the wrapper subprocess that executes the model-authored
- ``src/model.py``: the user's env minus credential-shaped vars
- (:func:`codeverse.proc.scrub_secrets`)."""
- env = scrub_secrets(dict(os.environ))
- env.pop("PYTHONSTARTUP", None)
- env.setdefault("OMP_NUM_THREADS", "4")
- env.setdefault("PYTHONUNBUFFERED", "1")
- return env
-
-
-class CadQueryRuntime:
- """LanguageRuntime for ``Language.CADQUERY``."""
-
- language = Language.CADQUERY
- entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.CADQUERY],)
-
- def __init__(self, *, python: str | None = None, settings: Settings | None = None, rlimit_gb: float = 8.0):
- self._settings = settings or get_settings()
- self._python = python or sys.executable
- self._rlimit_gb = rlimit_gb
-
- def entry_file(self, ws: Workspace) -> Path:
- return ws.src / "model.py"
-
- def build_command(self, ws: Workspace, *, seed: int = 0, tri_limit: int = MAX_TRIS_OBJECT,
- tolerance: float = 0.001, angular_tolerance: float = 0.15) -> list[str]:
- return [
- self._python, str(WRAPPER), "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),
- "--rlimit-gb", str(self._rlimit_gb), "--tri-limit", str(tri_limit), "--seed", str(seed),
- "--tolerance", str(tolerance), "--angular-tolerance", str(angular_tolerance),
- ]
-
- # ------------------------------------------------------------------ protocol
- def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
- if not isinstance(plan, StaticPlan):
- raise TypeError(f"CadQueryRuntime.skeleton needs a StaticPlan, got {type(plan).__name__}")
- return write_cadquery_skeleton(ws, plan)
-
- def lint(self, ws: Workspace) -> GateReport:
- return lint_cadquery_file(self.entry_file(ws))
-
- def build(self, ws: Workspace, *, timeout_s: int | None = None, seed: int = 0,
- tri_limit: int = MAX_TRIS_OBJECT) -> BuildResult:
- ws.artifacts.mkdir(parents=True, exist_ok=True)
- build_json, census_json = ws.artifacts / "build.json", ws.artifacts / "census.json"
- glb, step, stl = ws.artifacts / "object.glb", ws.artifacts / "object.step", ws.artifacts / "object.stl"
- # invalidate BEFORE the missing-entry early return (same reasoning as BlenderRuntime.build)
- ws.stage_artifacts("build.json", "census.json", "object.glb", "object.step", "object.stl").invalidate()
- entry = self.entry_file(ws)
- if not entry.is_file():
- result = BuildResult(ok=False, language=self.language.value, error_type="MissingEntryFile",
- error_message="src/model.py does not exist", error_file="src/model.py")
- ws.write_json(build_json, result)
- return result
- proc = run_subprocess(self.build_command(ws, seed=seed, tri_limit=tri_limit), cwd=ws.root, env=cadquery_env(),
- timeout_s=timeout_s or self._settings.limits.build_timeout_s)
- return compose_build_result(language=self.language.value, proc=proc, build_json=build_json, census_json=census_json,
- glb_path=glb, extra_paths={"step": step, "stl": stl})
-
- def contract_doc(self) -> str:
- p = PROMPTS_DIR / "cadquery" / "contract.md"
- if p.is_file():
- return p.read_text()
- return (_PKG_DIR / "CONTRACT.md").read_text()
-
- def cookbook_path(self) -> Path:
- return PROMPTS_DIR / "cadquery" / "cookbook.md"
diff --git a/harness/codeverse/languages/cadquery/skeleton.py b/harness/codeverse/languages/cadquery/skeleton.py
deleted file mode 100644
index 9273ee2d..00000000
--- a/harness/codeverse/languages/cadquery/skeleton.py
+++ /dev/null
@@ -1,109 +0,0 @@
-"""Starter ``src/model.py`` for the cadquery language, generated from a plan.
-
-Buildable as written: a ``cq.Assembly`` of placeholder boxes at the plan bboxes
-(instances laid out by symmetry), each named and coloured, so the agent starts
-from a green build and replaces ``build_<part>()`` bodies. Raw cadquery only.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from codeverse.contracts.plan import PartPlan, StaticPlan
-from codeverse.conventions import to_pascal, to_snake
-from codeverse.languages.blender.skeleton import finish_for, instance_centers
-from codeverse.workspace import Workspace
-
-
-def _fmt(v: tuple[float, float, float]) -> str:
- return "(" + ", ".join(f"{x:.3f}" for x in v) + ")"
-
-
-def _part_function(p: PartPlan) -> str:
- pascal, snake = to_pascal(p.name), to_snake(p.name)
- mn, mx = p.bbox.min, p.bbox.max
- ex, ey, ez = p.bbox.extents
- lines = [
- f"def build_{snake}():",
- f' """{pascal} — {p.role}',
- f" {p.description}",
- f" Material: {p.material or 'n/a'}",
- f" Plan bbox (world, Z-up): center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}",
- f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
- ]
- if p.attach_to:
- lines.append(f" Attaches to: {to_pascal(p.attach_to)} (faces must touch; small overlaps are fine)")
- if p.instances > 1:
- lines.append(f" Instances: {p.instances} ({p.symmetry}); build ONE centred at the origin, main() places each copy.")
- lines.append(' """')
- lines.append(" # TODO: replace the placeholder box (keep it centred on the origin; placement happens in main())")
- lines.append(f" return cq.Workplane(\"XY\").box({ex:.3f}, {ey:.3f}, {ez:.3f})")
- else:
- lines.append(' """')
- lines.append(" # TODO: replace the placeholder box with the real geometry (keep the name + bbox)")
- lines.append(f" return cq.Workplane(\"XY\").box({ex:.3f}, {ey:.3f}, {ez:.3f}).translate({_fmt(p.bbox.center)})")
- lines += ["", ""]
- return "\n".join(lines)
-
-
-def _main_body(plan: StaticPlan) -> str:
- lines = [f'result = cq.Assembly(name="{to_pascal(plan.object_name)}")', ""]
- for p in plan.parts:
- pascal, snake = to_pascal(p.name), to_snake(p.name)
- rgb, _r, _m = finish_for(f"{p.material} {p.description}")
- color = f"cq.Color({rgb[0]:.2f}, {rgb[1]:.2f}, {rgb[2]:.2f})"
- if p.instances == 1:
- lines.append(f'result.add(build_{snake}(), name="{pascal}", color={color})')
- continue
- centers = instance_centers(p.bbox, p.instances, p.symmetry)
- lines.append(f"_{snake} = build_{snake}()")
- lines.append(f"for _i, _c in enumerate({[tuple(round(x, 4) for x in c) for c in centers]}): # TODO: exact placement")
- lines.append(f' result.add(_{snake}, name=f"{pascal}_{{_i}}", loc=cq.Location(cq.Vector(*_c)), color={color})')
- lines.append("")
- return "\n".join(lines)
-
-
-def cadquery_skeleton_source(plan: StaticPlan) -> str:
- """Return the complete starter ``model.py`` text for ``plan``."""
- ob = plan.overall_bbox
- parts_doc = "\n".join(
- f" - {to_pascal(p.name)}{'' if p.instances == 1 else f' x{p.instances}'}: {p.role}; bbox center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}"
- for p in plan.parts
- )
- accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
- header = f'''"""{plan.object_name} — CadQuery model.
-
-{plan.summary}
-Style: {plan.style_notes or "n/a"}
-
-CONTRACT (the harness imports this file and exports `result` to GLB/STEP/STL itself):
- * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
- * Overall bbox: center {_fmt(ob.center)} extents {_fmt(ob.extents)}
- -> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
- * `result` = cq.Assembly; one `.add(shape, name="PascalName", color=cq.Color(r, g, b))` per part,
- instances Name_0..Name_N-1 (a shape built at the origin + `loc=cq.Location(cq.Vector(x, y, z))`).
- * Only `import cadquery as cq` (+ math / random). No file IO, no export, no show_object.
- * `.box(x, y, z)` is centred; `.cylinder(height, radius)`; `.rotate(p1, p2, DEGREES)`;
- `.translate()/.rotate()` return NEW objects (reassign). Keep fillet radius < 0.45 x wall thickness.
-
-PARTS:
-{parts_doc}
-
-ACCEPTANCE:
-{accept}
-"""
-import math # noqa: F401
-
-import cadquery as cq
-
-
-'''
- body = "".join(_part_function(p) for p in plan.parts)
- return header + body + _main_body(plan)
-
-
-def write_cadquery_skeleton(ws: Workspace, plan: StaticPlan) -> list[Path]:
- ws.src.mkdir(parents=True, exist_ok=True)
- path = ws.src / "model.py"
- path.write_text(cadquery_skeleton_source(plan))
- return [path]
diff --git a/harness/codeverse/languages/file_lint.py b/harness/codeverse/languages/file_lint.py
index c8b3a48b..715ed36c 100644
--- a/harness/codeverse/languages/file_lint.py
+++ b/harness/codeverse/languages/file_lint.py
@@ -58,22 +58,22 @@ def _errors(findings: list[GateFinding], max_errors: int) -> FileVerdict:
def _python(language: Language, rel: str, text: str, max_errors: int) -> FileVerdict:
name = Path(rel).name
if language is Language.BLENDER:
- from codeverse.languages.blender.lint import lint_blender_source
+ from codeverse.languages.blender import lint_blender_source
# same per-file settings as blender.layout.lint_workspace: helpers (_x.py) need no bpy;
# PascalCase-name checks are WARNs anyway and never reported here
rep = lint_blender_source(text, target=rel, expect_names=False, expect_bpy=not name.startswith("_"))
return _errors(rep.findings, max_errors)
if language is Language.CADQUERY:
- from codeverse.languages.cadquery.lint import lint_cadquery_source
+ from codeverse.languages.cadquery import lint_cadquery_source
return _errors(lint_cadquery_source(text, target=rel).findings, max_errors)
if language is Language.OPENGL_PYTHON:
- from codeverse.languages.opengl_python.lint import lint_source
+ from codeverse.languages.opengl_python import lint_source
return _errors(lint_source(text), max_errors)
if language is Language.URDF_BLENDER:
- from codeverse.languages.urdf.lint import lint_model_text
+ from codeverse.languages.urdf import lint_model_text
# link names are the urdf's business; here only syntax + forbidden APIs + `import bpy`
return _errors(lint_model_text(text, [], label=rel), max_errors)
@@ -94,7 +94,7 @@ def _js(path: Path, max_errors: int) -> FileVerdict:
def _glsl(rel: str, text: str, path: Path, max_errors: int) -> FileVerdict:
- from codeverse.languages.glsl_shader import lint as gl
+ import codeverse.languages.glsl_shader as gl
role = {gl.SHADER: "shader", gl.COMMON: "common", gl.BUFFER_A: "buffer_a"}.get(rel, "shader")
# the harness-owned recipe file beside it reserves its names (redefines_recipe)
@@ -104,7 +104,7 @@ def _glsl(rel: str, text: str, path: Path, max_errors: int) -> FileVerdict:
def _urdf(rel: str, text: str, max_errors: int) -> FileVerdict:
- from codeverse.languages.urdf.lint import lint_urdf_text
+ from codeverse.languages.urdf import lint_urdf_text
findings, _links = lint_urdf_text(text, label=rel)
return _errors(findings, max_errors)
diff --git a/harness/codeverse/languages/glsl_shader/__init__.py b/harness/codeverse/languages/glsl_shader/__init__.py
index f7ae15dd..e3c27b55 100644
--- a/harness/codeverse/languages/glsl_shader/__init__.py
+++ b/harness/codeverse/languages/glsl_shader/__init__.py
@@ -1,5 +1,466 @@
"""glsl_shader language: Shadertoy-style fragment shaders rendered by moderngl."""
-from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
+from __future__ import annotations
-__all__ = ["GlslShaderRuntime"]
+import re
+from collections.abc import Collection
+from dataclasses import dataclass
+from pathlib import Path
+
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.plan import GraphicsPlan, Plan
+from codeverse.languages._gl_common import ( # noqa: F401 — re-exported
+ GlslMessage,
+ LineMap,
+ Segment,
+ finish_build,
+ invalidate_stale_outputs,
+ judge_times,
+ load_plan,
+ make_host,
+ parse_glsl_log,
+ preview_times,
+ resolution_for,
+)
+from codeverse.prompts import PROMPTS_DIR, load_text
+from codeverse.spatial.gl_render import GlHost, GlResult
+from codeverse.workspace import Workspace
+
+# ===================================================================== wrap
+# (merged from codeverse/languages/glsl_shader/wrap.py, 2026-08-28)
+UNIFORM_NAMES: tuple[str, ...] = ("u_time", "u_resolution", "u_mouse", "u_frame", "u_prev", "u_noise", "u_buffer_a")
+
+HEADER = """#version 330 core
+// ---- harness header (do not write these lines yourself) ----
+uniform float u_time; // seconds
+uniform vec2 u_resolution; // pixels
+uniform vec2 u_mouse; // pixels (always 0,0 headless)
+uniform int u_frame; // frame counter
+uniform sampler2D u_prev; // previous frame of THIS pass (feedback)
+uniform sampler2D u_noise; // 256x256 RGBA white noise, repeat, linear
+uniform sampler2D u_buffer_a;// output of src/buffer_a.frag (when present)
+#define iTime u_time
+#define iResolution vec3(u_resolution, 1.0)
+#define iFrame u_frame
+#define iMouse vec4(u_mouse, 0.0, 0.0)
+#define iTimeDelta (1.0/30.0)
+#define iChannel0 u_prev
+#define iChannel1 u_noise
+out vec4 fragColor; // the ONLY output; write it in mainImage()/main()
+"""
+
+MAIN_IMAGE_TRAILER = """
+// ---- harness trailer ----
+void main() { mainImage(fragColor, gl_FragCoord.xy); }
+"""
+
+_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.S)
+_LINE_COMMENT = re.compile(r"//[^\n]*")
+_MAIN_IMAGE = re.compile(r"\bvoid\s+mainImage\s*\(")
+_PLAIN_MAIN = re.compile(r"\bvoid\s+main\s*\(\s*(void)?\s*\)")
+_OUT_DECL = re.compile(r"\bout\s+vec4\s+\w+\s*;")
+
+
+@dataclass
+class Composed:
+ source: str
+ line_map: LineMap
+ convention: str # "mainImage" | "main"
+ uses_feedback: bool
+
+
+def strip_comments(text: str) -> str:
+ """Blank out comments but keep every newline so line numbers stay valid."""
+ def _blank(m: re.Match[str]) -> str:
+ return re.sub(r"[^\n]", " ", m.group(0))
+
+ return _LINE_COMMENT.sub(_blank, _BLOCK_COMMENT.sub(_blank, text))
+
+
+def detect_convention(shader_src: str) -> str:
+ shader_src = strip_comments(shader_src)
+ if _MAIN_IMAGE.search(shader_src):
+ return "mainImage"
+ if _PLAIN_MAIN.search(shader_src):
+ return "main"
+ return "mainImage" # trailer will surface "mainImage undeclared" at compile time → clear error
+
+
+def _count(text: str) -> int:
+ return text.count("\n") + (0 if text.endswith("\n") else 1)
+
+
+def _piece(text: str) -> str:
+ return text if text.endswith("\n") else text + "\n"
+
+
+def compose(shader_src: str, common_src: str | None = None, *, recipes_src: str | None = None,
+ shader_file: str = "src/shader.frag", common_file: str = "src/common.glsl",
+ recipes_file: str = "src/recipes.glsl") -> Composed:
+ """Header + recipes (harness-owned, first: self-contained, nothing in common.glsl can shadow it)
+ + common + shader (+ trailer) with a line map back to the agent files."""
+ convention = detect_convention(shader_src)
+ pieces: list[tuple[str, str]] = [("harness", HEADER)]
+ if recipes_src and recipes_src.strip():
+ pieces.append((recipes_file, _piece(recipes_src)))
+ if common_src and common_src.strip():
+ pieces.append((common_file, _piece(common_src)))
+ pieces.append((shader_file, _piece(shader_src)))
+ if convention == "mainImage":
+ pieces.append(("harness", MAIN_IMAGE_TRAILER))
+ segments: list[Segment] = []
+ cursor = 1
+ out: list[str] = []
+ for name, text in pieces:
+ n = _count(text)
+ segments.append(Segment(name, cursor, n))
+ cursor += n
+ out.append(text)
+ src = "".join(out)
+ code = strip_comments(shader_src) + "\n" + strip_comments(common_src or "") + "\n" + strip_comments(recipes_src or "")
+ uses_feedback = "u_prev" in code or "iChannel0" in code
+ return Composed(source=src, line_map=LineMap(segments), convention=convention, uses_feedback=uses_feedback)
+
+
+# --------------------------------------------------------------------------- compiler messages
+# GlslMessage / LineMap / parse_glsl_log live in ``_gl_common`` (shared with opengl_python)
+# and are re-exported above; only source composition + first_error remain here.
+def first_error(messages: list[GlslMessage]) -> GlslMessage | None:
+ for m in messages:
+ if m.kind == "error":
+ return m
+ return None
+
+
+# ===================================================================== lint
+# (merged from codeverse/languages/glsl_shader/lint.py, 2026-08-28)
+GATE = "lint:glsl_shader"
+SHADER = "src/shader.frag"
+COMMON = "src/common.glsl"
+BUFFER_A = "src/buffer_a.frag"
+#: harness-owned (``contracts.common.HARNESS_OWNED_SRC``): seeded cookbook recipes, pasted above common.glsl
+RECIPES = "src/recipes.glsl"
+#: a top-level GLSL function definition, ``group(1)`` = its name (match per line)
+FUNC_DEF = re.compile(r"^[ \t]*(?:float|int|bool|void|[bi]?vec[234]|mat[234])\s+(\w+)\s*\(")
+SAMPLERS = {"u_prev", "u_noise", "u_buffer_a", "iChannel0", "iChannel1"}
+MAX_CHARS = 60_000
+
+_VERSION = re.compile(r"^[ \t]*#[ \t]*version\b", re.M)
+_INCLUDE = re.compile(r"^[ \t]*#[ \t]*include\b", re.M)
+_UNIFORM_DECL = re.compile(r"\buniform\s+\w+\s+(\w+)")
+_OUT_DECL = re.compile(r"^[ \t]*(?:layout\s*\([^)]*\)\s*)?out\s+vec4\s+(\w+)\s*;", re.M)
+_TEXTURE = re.compile(r"\btexture(?:Lod|Grad|Proj)?\s*\(\s*(\w+)")
+_MISSING_INPUTS = re.compile(r"\b(iChannel[23]|iChannelResolution|iChannelTime|iDate|iSampleRate|iFrameRate)\b")
+_LEGACY = {
+ "gl_FragColor": "write `fragColor` (declared by the harness) instead of gl_FragColor",
+ "texture2D(": "use `texture(sampler, uv)` — GLSL 330 has no texture2D",
+ "varying ": "fragment-only shader: no varyings; use gl_FragCoord / uniforms",
+ "attribute ": "fragment-only shader: no attributes",
+}
+_FLOAT_LITERAL_MOD = re.compile(r"(\d\.\d*|\.\d+)\s*%|%\s*(\d\.\d*|\.\d+)")
+_PRECISION = re.compile(r"^[ \t]*precision\s+(lowp|mediump|highp)\s+\w+\s*;", re.M)
+def _line_of(text: str, pos: int) -> int:
+ return text.count("\n", 0, pos) + 1
+
+
+def defined_functions(text: str) -> dict[str, int]:
+ """``{name: line}`` of every top-level function definition in a GLSL text (comments blanked)."""
+ out: dict[str, int] = {}
+ for i, line in enumerate(strip_comments(text).splitlines(), 1):
+ if (m := FUNC_DEF.match(line)) and m.group(1) not in out:
+ out[m.group(1)] = i
+ return out
+
+
+def _check_file(rel: str, text: str, *, role: str, recipe_names: Collection[str] = ()) -> list[GateFinding]:
+ out: list[GateFinding] = []
+ raw_len = len(text)
+ text = strip_comments(text)
+
+ def add(sev: Severity, kind: str, msg: str, hint: str, line: int | None = None) -> None:
+ out.append(GateFinding(gate=GATE, severity=sev, target=rel, message=(f"{rel}:{line}: " if line else f"{rel}: ") + msg,
+ fix_hint=hint, data={"kind": kind, "line": line, "file": rel}))
+
+ if raw_len > MAX_CHARS:
+ add(Severity.WARN, "too_long", f"file is {raw_len} chars; keep shaders compact", "remove dead code; move helpers to src/common.glsl")
+ for m in _VERSION.finditer(text):
+ add(Severity.ERROR, "version_line", "contains a #version line; the harness prepends `#version 330 core`",
+ "delete the #version line", _line_of(text, m.start()))
+ for m in _INCLUDE.finditer(text):
+ add(Severity.ERROR, "include", "#include is not GLSL; src/common.glsl is pasted in automatically",
+ "delete the #include line; functions in src/common.glsl are already visible", _line_of(text, m.start()))
+ for m in _UNIFORM_DECL.finditer(text):
+ name = m.group(1)
+ if name in UNIFORM_NAMES:
+ add(Severity.ERROR, "redeclared_uniform", f"redeclares harness uniform `{name}`",
+ f"delete the declaration; `{name}` is provided by the harness header", _line_of(text, m.start()))
+ else:
+ add(Severity.ERROR, "custom_uniform", f"declares uniform `{name}` which nothing will set",
+ "only u_time / u_resolution / u_mouse / u_frame / u_prev / u_noise / u_buffer_a exist; turn it into a `const`",
+ _line_of(text, m.start()))
+ for m in _OUT_DECL.finditer(text):
+ add(Severity.ERROR, "redeclared_output", f"declares output `{m.group(1)}`; the harness already declares `out vec4 fragColor`",
+ "delete the `out vec4 ...;` line and write to fragColor", _line_of(text, m.start()))
+ for m in _TEXTURE.finditer(text):
+ name = m.group(1)
+ if name not in SAMPLERS:
+ add(Severity.ERROR, "undeclared_sampler", f"texture() reads sampler `{name}` which does not exist",
+ "only u_prev (previous frame), u_noise (256² RGBA noise) and u_buffer_a (buffer pass) can be sampled; "
+ "generate patterns procedurally (hash/noise/fbm from the cookbook)", _line_of(text, m.start()))
+ for m in _MISSING_INPUTS.finditer(text):
+ add(Severity.ERROR, "missing_input", f"`{m.group(1)}` is not available in this harness",
+ "available: u_time/iTime, u_resolution/iResolution, u_frame/iFrame, u_mouse (always 0), u_prev/iChannel0, u_noise/iChannel1",
+ _line_of(text, m.start()))
+ for needle, hint in _LEGACY.items():
+ pos = text.find(needle)
+ if pos >= 0:
+ add(Severity.ERROR, "legacy_glsl", f"uses `{needle.strip()}` (GLSL 1.x)", hint, _line_of(text, pos))
+ for m in _FLOAT_LITERAL_MOD.finditer(text):
+ add(Severity.ERROR, "float_modulo", "`%` on a float literal — GLSL `%` is integer-only", "use mod(x, y)", _line_of(text, m.start()))
+ for name, line in defined_functions(text).items():
+ if name in recipe_names:
+ add(Severity.ERROR, "redefines_recipe", f"`{name}` is already provided by {RECIPES} — call it instead of redefining it",
+ f"delete this `{name}` definition; {RECIPES} is harness-owned and pasted above your code, so its `{name}` is in scope", line)
+ if role in ("shader", "buffer_a"):
+ if not _MAIN_IMAGE.search(text) and not _PLAIN_MAIN.search(text):
+ add(Severity.ERROR, "no_entry", "neither `void mainImage(out vec4 fragColor, in vec2 fragCoord)` nor `void main()` found",
+ "define `void mainImage(out vec4 fragColor, in vec2 fragCoord) { ... fragColor = vec4(col, 1.0); }`")
+ if "fragColor" not in text and "gl_FragColor" not in text:
+ add(Severity.ERROR, "no_output", "never writes fragColor", "end mainImage()/main() with `fragColor = vec4(col, 1.0);`")
+ if role == "common" and (_MAIN_IMAGE.search(text) or _PLAIN_MAIN.search(text)):
+ add(Severity.ERROR, "entry_in_common", "src/common.glsl must not define main()/mainImage()",
+ "move the entry point to src/shader.frag; keep only helper functions / constants in common.glsl")
+ if role == "buffer_a" and "u_buffer_a" in text:
+ add(Severity.WARN, "buffer_self_ref", "buffer_a.frag samples u_buffer_a; inside the buffer pass the previous buffer is `u_prev`",
+ "use texture(u_prev, uv) for feedback inside buffer_a.frag")
+ for m in _PRECISION.finditer(text):
+ add(Severity.INFO, "precision", "precision qualifier is ignored on desktop GLSL 330", "safe to delete", _line_of(text, m.start()))
+ if "u_mouse" in text or "iMouse" in text:
+ add(Severity.INFO, "mouse", "u_mouse is always (0,0) when rendered headless", "do not depend on the mouse for the look")
+ return out
+
+
+def recipe_names(ws: Workspace) -> frozenset[str]:
+ """The names the harness-owned ``src/recipes.glsl`` provides (empty when nothing was seeded)."""
+ p = ws.root / RECIPES
+ return frozenset(defined_functions(p.read_text(errors="replace"))) if p.is_file() else frozenset()
+
+
+def lint_workspace(ws: Workspace) -> GateReport:
+ findings: list[GateFinding] = []
+ reserved = recipe_names(ws)
+ shader = ws.root / SHADER
+ if not shader.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=SHADER, message=f"{SHADER} is missing",
+ fix_hint="create src/shader.frag with a mainImage(out vec4 fragColor, in vec2 fragCoord) function",
+ data={"kind": "missing_entry", "file": SHADER}))
+ else:
+ findings.extend(_check_file(SHADER, shader.read_text(errors="replace"), role="shader", recipe_names=reserved))
+ for rel, role in ((COMMON, "common"), (BUFFER_A, "buffer_a")):
+ p = ws.root / rel
+ if p.is_file():
+ findings.extend(_check_file(rel, p.read_text(errors="replace"), role=role, recipe_names=reserved))
+ stray = [str(p.relative_to(ws.root)) for p in ws.src.rglob("*") if p.is_file()
+ and str(p.relative_to(ws.root)) not in (SHADER, COMMON, BUFFER_A, RECIPES) and p.suffix in (".frag", ".glsl", ".vert", ".py", ".js")]
+ for rel in stray:
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel} is not part of the shader contract and is ignored",
+ fix_hint="keep code in src/shader.frag (+ src/common.glsl, src/buffer_a.frag)", data={"kind": "stray_file", "file": rel}))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings)
+
+
+def lint_text(shader_src: str, common_src: str | None = None, buffer_a_src: str | None = None, *,
+ recipes_src: str | None = None) -> list[GateFinding]:
+ """Lint in-memory sources (tools / tests); ``recipes_src`` is the harness-owned recipe file whose
+ names the agent files may not redefine (it is not linted itself)."""
+ reserved = frozenset(defined_functions(recipes_src)) if recipes_src else frozenset()
+ out = _check_file(SHADER, shader_src, role="shader", recipe_names=reserved)
+ if common_src is not None:
+ out += _check_file(COMMON, common_src, role="common", recipe_names=reserved)
+ if buffer_a_src is not None:
+ out += _check_file(BUFFER_A, buffer_a_src, role="buffer_a", recipe_names=reserved)
+ return out
+
+
+# ===================================================================== skeleton
+# (merged from codeverse/languages/glsl_shader/skeleton.py, 2026-08-28)
+COMMON_GLSL = """// src/common.glsl — helpers pasted above shader.frag by the harness (no #include needed).
+// Keep ONLY functions / constants here; no main(), no uniforms, no #version.
+#define PI 3.14159265359
+#define TAU 6.28318530718
+
+float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); }
+float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
+
+// value noise 2D (smooth, 0..1)
+float noise(vec2 p) {
+ vec2 i = floor(p), f = fract(p);
+ vec2 u = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x),
+ mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
+}
+
+// fractal brownian motion, 5 octaves (constant loop bound)
+float fbm(vec2 p) {
+ float v = 0.0, a = 0.5;
+ mat2 rot = mat2(0.8, 0.6, -0.6, 0.8);
+ for (int i = 0; i < 5; i++) { v += a * noise(p); p = rot * p * 2.02; a *= 0.5; }
+ return v;
+}
+
+mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }
+
+// cosine palette (IQ): t in 0..1
+vec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) { return a + b * cos(TAU * (c * t + d)); }
+
+// filmic-ish tonemap + gamma
+vec3 tonemap(vec3 c) { c = c / (1.0 + c); return pow(clamp(c, 0.0, 1.0), vec3(1.0 / 2.2)); }
+"""
+
+_SHADER_TEMPLATE = """// src/shader.frag — {title}
+// CONTRACT (the harness prepends `#version 330 core` + these uniforms + `out vec4 fragColor`; DO NOT redeclare them):
+// uniform float u_time; uniform vec2 u_resolution; uniform vec2 u_mouse; uniform int u_frame;
+// uniform sampler2D u_prev; (previous frame of this pass) uniform sampler2D u_noise; (256x256 RGBA noise, repeat)
+// uniform sampler2D u_buffer_a; (output of src/buffer_a.frag when that file exists)
+// iTime / iResolution / iFrame / iMouse / iChannel0(=u_prev) / iChannel1(=u_noise) are #defined for Shadertoy ports.
+// Entry: void mainImage(out vec4 fragColor, in vec2 fragCoord) — fragCoord in pixels, origin BOTTOM-LEFT.
+// Helpers available from src/common.glsl: hash11 hash12 hash22 noise fbm rot2 palette tonemap PI TAU.
+// Duration {duration:g}s; judged frames at t = 0, 1, 2.5, 4, 6 s. Everything must MOVE with u_time.
+//
+// PLAN — {summary}
+// Style: {style}
+{passes}
+{visuals}
+// Motion: {motion}
+
+void mainImage(out vec4 fragColor, in vec2 fragCoord) {{
+ vec2 uv = fragCoord / u_resolution.xy; // 0..1
+ vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // aspect-correct, centred
+ float t = u_time;
+
+ // TODO replace this placeholder look with the plan's passes above
+ vec3 sky = mix(vec3(0.95, 0.55, 0.25), vec3(0.10, 0.20, 0.45), smoothstep(-0.2, 0.6, p.y));
+ vec2 sunPos = vec2(0.35 * cos(t * 0.3), 0.15 + 0.1 * sin(t * 0.3));
+ float sun = exp(-40.0 * length(p - sunPos));
+ float haze = fbm(p * 3.0 + vec2(t * 0.15, 0.0));
+ vec3 col = sky + vec3(1.0, 0.8, 0.5) * sun + 0.25 * haze * vec3(0.9, 0.7, 0.6);
+ col *= 1.0 - 0.35 * length(p); // vignette
+ fragColor = vec4(tonemap(col), 1.0);
+}}
+"""
+
+
+def _comment_lines(prefix: str, items: list[str]) -> str:
+ if not items:
+ return f"// {prefix}: (none)"
+ return "\n".join(f"// TODO {prefix} {i + 1}: {x}" for i, x in enumerate(items))
+
+
+def shader_source(plan: GraphicsPlan | None) -> str:
+ title = plan.title if plan else "untitled shader"
+ summary = plan.summary if plan else ""
+ style = plan.style if plan else ""
+ motion = plan.motion if plan else "animate with u_time"
+ duration = plan.duration_s if plan else 8.0
+ passes = [f"{p.name} ({p.kind}): {p.description}" for p in plan.passes] if plan else []
+ visuals = list(plan.key_visuals) if plan else []
+ return _SHADER_TEMPLATE.format(
+ title=title, summary=summary, style=style, motion=motion, duration=duration,
+ passes=_comment_lines("pass", passes), visuals=_comment_lines("key visual", visuals),
+ )
+
+
+def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
+ gplan = plan if isinstance(plan, GraphicsPlan) else None
+ ws.src.mkdir(parents=True, exist_ok=True)
+ common = ws.src / "common.glsl"
+ shader = ws.src / "shader.frag"
+ common.write_text(COMMON_GLSL)
+ shader.write_text(shader_source(gplan))
+ return [common, shader]
+
+
+# ===================================================================== runtime
+# (merged from codeverse/languages/glsl_shader/runtime.py, 2026-08-28)
+CONTRACT_FALLBACK = """src/shader.frag — GLSL 330 fragment shader body (NO #version line, NO uniform declarations):
+write `void mainImage(out vec4 fragColor, in vec2 fragCoord)` using the harness uniforms u_time, u_resolution,
+u_mouse, u_frame, u_prev (previous frame), u_noise (256² noise), u_buffer_a (src/buffer_a.frag output).
+Optional src/common.glsl (helpers, pasted in first) and src/buffer_a.frag (one feedback pass). Animate with u_time."""
+
+
+class GlslShaderRuntime:
+ language = Language.GLSL_SHADER
+ entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.GLSL_SHADER], COMMON, BUFFER_A)
+
+ def __init__(self, *, host: GlHost | None = None):
+ self._host = host
+
+ # ------------------------------------------------------------------ contract
+ def contract_doc(self) -> str:
+ try:
+ return load_text("glsl_shader/contract.md")
+ except FileNotFoundError:
+ return CONTRACT_FALLBACK
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "glsl_shader" / "cookbook.md"
+
+ # ------------------------------------------------------------------ skeleton / lint
+ def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ # ------------------------------------------------------------------ build
+ def host(self, timeout_s: float | None = None) -> GlHost:
+ return make_host(self._host, timeout_s)
+
+ def compose_sources(self, ws: Workspace) -> tuple[Composed, Composed | None]:
+ shader = (ws.root / SHADER).read_text(errors="replace")
+ common_p = ws.root / COMMON
+ common = common_p.read_text(errors="replace") if common_p.is_file() else None
+ recipes_p = ws.root / RECIPES
+ recipes = recipes_p.read_text(errors="replace") if recipes_p.is_file() else None
+ image = compose(shader, common, recipes_src=recipes)
+ buf_p = ws.root / BUFFER_A
+ buffer_a = (compose(buf_p.read_text(errors="replace"), common, recipes_src=recipes, shader_file=BUFFER_A)
+ if buf_p.is_file() else None)
+ return image, buffer_a
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None, times: list[float] | None = None,
+ preview: bool = True, width: int | None = None, height: int | None = None) -> BuildResult:
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ invalidate_stale_outputs(ws) # BEFORE the MissingEntry return, so it also clears
+ if not (ws.root / SHADER).is_file():
+ res = GlResult(ok=False, mode="shader", stage="lint", error_type="MissingEntry", error_message=f"{SHADER} is missing")
+ return finish_build(ws, res, language=self.language.value, error_file=SHADER)
+ plan = load_plan(ws)
+ w, h = resolution_for(plan)
+ if width and height:
+ w, h = int(width), int(height)
+ duration = plan.duration_s if plan else None
+ image, buffer_a = self.compose_sources(ws)
+ host = self.host(timeout_s)
+ res = host.render_fragment_shader(
+ image.source, ws.artifacts, width=w, height=h, times=times or judge_times(duration),
+ buffer_a_src=buffer_a.source if buffer_a else None, feedback=image.uses_feedback or buffer_a is not None,
+ extra_times=preview_times(duration) if preview else (),
+ )
+ census = {"convention": image.convention, "has_common": (ws.root / COMMON).is_file(), "has_buffer_a": buffer_a is not None,
+ "has_recipes": (ws.root / RECIPES).is_file(), "resolution": [w, h]}
+ err_file, err_line, err_msg = "", None, None
+ if not res.ok and res.stage in ("compile", "compile_buffer_a"):
+ comp = buffer_a if res.stage == "compile_buffer_a" and buffer_a else image
+ msgs = parse_glsl_log(res.error_message, comp.line_map)
+ first = first_error(msgs)
+ if first is not None:
+ err_file, err_line = first.file, first.file_line
+ listed = "\n".join(m.text() for m in msgs[:12]) or res.error_message.strip()
+ err_msg = f"GLSL compile error ({'buffer_a' if res.stage == 'compile_buffer_a' else 'shader'}):\n{listed}"
+ res.error_type = "GlslCompileError"
+ motion_expected = bool(plan.motion.strip()) if plan else True
+ return finish_build(ws, res, language=self.language.value, error_file=err_file, error_line=err_line,
+ error_message=err_msg, census=census, motion_expected=motion_expected)
diff --git a/harness/codeverse/languages/glsl_shader/lint.py b/harness/codeverse/languages/glsl_shader/lint.py
deleted file mode 100644
index ec2b5dbd..00000000
--- a/harness/codeverse/languages/glsl_shader/lint.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""Static checks for ``src/shader.frag`` (+ ``common.glsl`` / ``buffer_a.frag``).
-
-Catches what the compiler reports confusingly (or too late): a ``#version`` line
-(the harness prepends one), redeclared harness uniforms / outputs, Shadertoy
-inputs that do not exist here (``iChannel2``, ``iDate`` …), ``texture()`` on
-undeclared samplers, GLSL 1.x syntax (``gl_FragColor`` / ``varying`` /
-``texture2D``), ``%`` on floats, a missing ``mainImage``/``main``, and a function
-the harness-owned ``src/recipes.glsl`` already provides defined again in an agent
-file (``redefines_recipe`` — the compiler would say "redefinition" at the second
-copy; this says which file owns the first). ``src/recipes.glsl`` itself is
-harness-verified and is not linted. Gate name ``lint:glsl_shader``;
-``data["kind"]`` names the rule.
-"""
-
-from __future__ import annotations
-
-import re
-from collections.abc import Collection
-
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.languages.glsl_shader.wrap import (
- _MAIN_IMAGE,
- _PLAIN_MAIN,
- UNIFORM_NAMES,
- strip_comments,
-)
-from codeverse.workspace import Workspace
-
-GATE = "lint:glsl_shader"
-SHADER = "src/shader.frag"
-COMMON = "src/common.glsl"
-BUFFER_A = "src/buffer_a.frag"
-#: harness-owned (``contracts.common.HARNESS_OWNED_SRC``): seeded cookbook recipes, pasted above common.glsl
-RECIPES = "src/recipes.glsl"
-#: a top-level GLSL function definition, ``group(1)`` = its name (match per line)
-FUNC_DEF = re.compile(r"^[ \t]*(?:float|int|bool|void|[bi]?vec[234]|mat[234])\s+(\w+)\s*\(")
-SAMPLERS = {"u_prev", "u_noise", "u_buffer_a", "iChannel0", "iChannel1"}
-MAX_CHARS = 60_000
-
-_VERSION = re.compile(r"^[ \t]*#[ \t]*version\b", re.M)
-_INCLUDE = re.compile(r"^[ \t]*#[ \t]*include\b", re.M)
-_UNIFORM_DECL = re.compile(r"\buniform\s+\w+\s+(\w+)")
-_OUT_DECL = re.compile(r"^[ \t]*(?:layout\s*\([^)]*\)\s*)?out\s+vec4\s+(\w+)\s*;", re.M)
-_TEXTURE = re.compile(r"\btexture(?:Lod|Grad|Proj)?\s*\(\s*(\w+)")
-_MISSING_INPUTS = re.compile(r"\b(iChannel[23]|iChannelResolution|iChannelTime|iDate|iSampleRate|iFrameRate)\b")
-_LEGACY = {
- "gl_FragColor": "write `fragColor` (declared by the harness) instead of gl_FragColor",
- "texture2D(": "use `texture(sampler, uv)` — GLSL 330 has no texture2D",
- "varying ": "fragment-only shader: no varyings; use gl_FragCoord / uniforms",
- "attribute ": "fragment-only shader: no attributes",
-}
-_FLOAT_LITERAL_MOD = re.compile(r"(\d\.\d*|\.\d+)\s*%|%\s*(\d\.\d*|\.\d+)")
-_PRECISION = re.compile(r"^[ \t]*precision\s+(lowp|mediump|highp)\s+\w+\s*;", re.M)
-def _line_of(text: str, pos: int) -> int:
- return text.count("\n", 0, pos) + 1
-
-
-def defined_functions(text: str) -> dict[str, int]:
- """``{name: line}`` of every top-level function definition in a GLSL text (comments blanked)."""
- out: dict[str, int] = {}
- for i, line in enumerate(strip_comments(text).splitlines(), 1):
- if (m := FUNC_DEF.match(line)) and m.group(1) not in out:
- out[m.group(1)] = i
- return out
-
-
-def _check_file(rel: str, text: str, *, role: str, recipe_names: Collection[str] = ()) -> list[GateFinding]:
- out: list[GateFinding] = []
- raw_len = len(text)
- text = strip_comments(text)
-
- def add(sev: Severity, kind: str, msg: str, hint: str, line: int | None = None) -> None:
- out.append(GateFinding(gate=GATE, severity=sev, target=rel, message=(f"{rel}:{line}: " if line else f"{rel}: ") + msg,
- fix_hint=hint, data={"kind": kind, "line": line, "file": rel}))
-
- if raw_len > MAX_CHARS:
- add(Severity.WARN, "too_long", f"file is {raw_len} chars; keep shaders compact", "remove dead code; move helpers to src/common.glsl")
- for m in _VERSION.finditer(text):
- add(Severity.ERROR, "version_line", "contains a #version line; the harness prepends `#version 330 core`",
- "delete the #version line", _line_of(text, m.start()))
- for m in _INCLUDE.finditer(text):
- add(Severity.ERROR, "include", "#include is not GLSL; src/common.glsl is pasted in automatically",
- "delete the #include line; functions in src/common.glsl are already visible", _line_of(text, m.start()))
- for m in _UNIFORM_DECL.finditer(text):
- name = m.group(1)
- if name in UNIFORM_NAMES:
- add(Severity.ERROR, "redeclared_uniform", f"redeclares harness uniform `{name}`",
- f"delete the declaration; `{name}` is provided by the harness header", _line_of(text, m.start()))
- else:
- add(Severity.ERROR, "custom_uniform", f"declares uniform `{name}` which nothing will set",
- "only u_time / u_resolution / u_mouse / u_frame / u_prev / u_noise / u_buffer_a exist; turn it into a `const`",
- _line_of(text, m.start()))
- for m in _OUT_DECL.finditer(text):
- add(Severity.ERROR, "redeclared_output", f"declares output `{m.group(1)}`; the harness already declares `out vec4 fragColor`",
- "delete the `out vec4 ...;` line and write to fragColor", _line_of(text, m.start()))
- for m in _TEXTURE.finditer(text):
- name = m.group(1)
- if name not in SAMPLERS:
- add(Severity.ERROR, "undeclared_sampler", f"texture() reads sampler `{name}` which does not exist",
- "only u_prev (previous frame), u_noise (256² RGBA noise) and u_buffer_a (buffer pass) can be sampled; "
- "generate patterns procedurally (hash/noise/fbm from the cookbook)", _line_of(text, m.start()))
- for m in _MISSING_INPUTS.finditer(text):
- add(Severity.ERROR, "missing_input", f"`{m.group(1)}` is not available in this harness",
- "available: u_time/iTime, u_resolution/iResolution, u_frame/iFrame, u_mouse (always 0), u_prev/iChannel0, u_noise/iChannel1",
- _line_of(text, m.start()))
- for needle, hint in _LEGACY.items():
- pos = text.find(needle)
- if pos >= 0:
- add(Severity.ERROR, "legacy_glsl", f"uses `{needle.strip()}` (GLSL 1.x)", hint, _line_of(text, pos))
- for m in _FLOAT_LITERAL_MOD.finditer(text):
- add(Severity.ERROR, "float_modulo", "`%` on a float literal — GLSL `%` is integer-only", "use mod(x, y)", _line_of(text, m.start()))
- for name, line in defined_functions(text).items():
- if name in recipe_names:
- add(Severity.ERROR, "redefines_recipe", f"`{name}` is already provided by {RECIPES} — call it instead of redefining it",
- f"delete this `{name}` definition; {RECIPES} is harness-owned and pasted above your code, so its `{name}` is in scope", line)
- if role in ("shader", "buffer_a"):
- if not _MAIN_IMAGE.search(text) and not _PLAIN_MAIN.search(text):
- add(Severity.ERROR, "no_entry", "neither `void mainImage(out vec4 fragColor, in vec2 fragCoord)` nor `void main()` found",
- "define `void mainImage(out vec4 fragColor, in vec2 fragCoord) { ... fragColor = vec4(col, 1.0); }`")
- if "fragColor" not in text and "gl_FragColor" not in text:
- add(Severity.ERROR, "no_output", "never writes fragColor", "end mainImage()/main() with `fragColor = vec4(col, 1.0);`")
- if role == "common" and (_MAIN_IMAGE.search(text) or _PLAIN_MAIN.search(text)):
- add(Severity.ERROR, "entry_in_common", "src/common.glsl must not define main()/mainImage()",
- "move the entry point to src/shader.frag; keep only helper functions / constants in common.glsl")
- if role == "buffer_a" and "u_buffer_a" in text:
- add(Severity.WARN, "buffer_self_ref", "buffer_a.frag samples u_buffer_a; inside the buffer pass the previous buffer is `u_prev`",
- "use texture(u_prev, uv) for feedback inside buffer_a.frag")
- for m in _PRECISION.finditer(text):
- add(Severity.INFO, "precision", "precision qualifier is ignored on desktop GLSL 330", "safe to delete", _line_of(text, m.start()))
- if "u_mouse" in text or "iMouse" in text:
- add(Severity.INFO, "mouse", "u_mouse is always (0,0) when rendered headless", "do not depend on the mouse for the look")
- return out
-
-
-def recipe_names(ws: Workspace) -> frozenset[str]:
- """The names the harness-owned ``src/recipes.glsl`` provides (empty when nothing was seeded)."""
- p = ws.root / RECIPES
- return frozenset(defined_functions(p.read_text(errors="replace"))) if p.is_file() else frozenset()
-
-
-def lint_workspace(ws: Workspace) -> GateReport:
- findings: list[GateFinding] = []
- reserved = recipe_names(ws)
- shader = ws.root / SHADER
- if not shader.is_file():
- findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=SHADER, message=f"{SHADER} is missing",
- fix_hint="create src/shader.frag with a mainImage(out vec4 fragColor, in vec2 fragCoord) function",
- data={"kind": "missing_entry", "file": SHADER}))
- else:
- findings.extend(_check_file(SHADER, shader.read_text(errors="replace"), role="shader", recipe_names=reserved))
- for rel, role in ((COMMON, "common"), (BUFFER_A, "buffer_a")):
- p = ws.root / rel
- if p.is_file():
- findings.extend(_check_file(rel, p.read_text(errors="replace"), role=role, recipe_names=reserved))
- stray = [str(p.relative_to(ws.root)) for p in ws.src.rglob("*") if p.is_file()
- and str(p.relative_to(ws.root)) not in (SHADER, COMMON, BUFFER_A, RECIPES) and p.suffix in (".frag", ".glsl", ".vert", ".py", ".js")]
- for rel in stray:
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel} is not part of the shader contract and is ignored",
- fix_hint="keep code in src/shader.frag (+ src/common.glsl, src/buffer_a.frag)", data={"kind": "stray_file", "file": rel}))
- passed = not any(f.severity == Severity.ERROR for f in findings)
- return GateReport(gate=GATE, passed=passed, findings=findings)
-
-
-def lint_text(shader_src: str, common_src: str | None = None, buffer_a_src: str | None = None, *,
- recipes_src: str | None = None) -> list[GateFinding]:
- """Lint in-memory sources (tools / tests); ``recipes_src`` is the harness-owned recipe file whose
- names the agent files may not redefine (it is not linted itself)."""
- reserved = frozenset(defined_functions(recipes_src)) if recipes_src else frozenset()
- out = _check_file(SHADER, shader_src, role="shader", recipe_names=reserved)
- if common_src is not None:
- out += _check_file(COMMON, common_src, role="common", recipe_names=reserved)
- if buffer_a_src is not None:
- out += _check_file(BUFFER_A, buffer_a_src, role="buffer_a", recipe_names=reserved)
- return out
-
-
-__all__ = ["GATE", "SHADER", "COMMON", "BUFFER_A", "RECIPES", "FUNC_DEF", "defined_functions", "recipe_names",
- "lint_workspace", "lint_text", "strip_comments"]
diff --git a/harness/codeverse/languages/glsl_shader/runtime.py b/harness/codeverse/languages/glsl_shader/runtime.py
deleted file mode 100644
index 66a004ca..00000000
--- a/harness/codeverse/languages/glsl_shader/runtime.py
+++ /dev/null
@@ -1,114 +0,0 @@
-"""GlslShaderRuntime: skeleton → lint → build (moderngl frames) for Shadertoy-style shaders.
-
-``src/shader.frag`` (+ optional ``src/common.glsl``, ``src/buffer_a.frag``, and the
-harness-owned ``src/recipes.glsl`` when the track seeded recipes) is wrapped by
-:mod:`wrap` (header with the uniform contract + main trampoline; recipes pasted
-above common), compiled and rendered in a subprocess by :class:`GlHost` at the
-plan's resolution for t ∈ {0, 1, 2.5, 4, 6}s (+ preview frames for the GIF).
-Compile errors come back mapped to ``src/shader.frag:LINE`` (or common / recipes).
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from codeverse.contracts.artifacts import BuildResult, GateReport
-from codeverse.contracts.common import ENTRY_FILE, Language
-from codeverse.contracts.plan import Plan
-from codeverse.languages._gl_common import (
- finish_build,
- invalidate_stale_outputs,
- judge_times,
- load_plan,
- make_host,
- parse_glsl_log,
- preview_times,
- resolution_for,
-)
-from codeverse.languages.glsl_shader.lint import BUFFER_A, COMMON, RECIPES, SHADER, lint_workspace
-from codeverse.languages.glsl_shader.skeleton import write_skeleton
-from codeverse.languages.glsl_shader.wrap import Composed, compose, first_error
-from codeverse.prompts import PROMPTS_DIR, load_text
-from codeverse.spatial.gl_render import GlHost, GlResult
-from codeverse.workspace import Workspace
-
-CONTRACT_FALLBACK = """src/shader.frag — GLSL 330 fragment shader body (NO #version line, NO uniform declarations):
-write `void mainImage(out vec4 fragColor, in vec2 fragCoord)` using the harness uniforms u_time, u_resolution,
-u_mouse, u_frame, u_prev (previous frame), u_noise (256² noise), u_buffer_a (src/buffer_a.frag output).
-Optional src/common.glsl (helpers, pasted in first) and src/buffer_a.frag (one feedback pass). Animate with u_time."""
-
-
-class GlslShaderRuntime:
- language = Language.GLSL_SHADER
- entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.GLSL_SHADER], COMMON, BUFFER_A)
-
- def __init__(self, *, host: GlHost | None = None):
- self._host = host
-
- # ------------------------------------------------------------------ contract
- def contract_doc(self) -> str:
- try:
- return load_text("glsl_shader/contract.md")
- except FileNotFoundError:
- return CONTRACT_FALLBACK
-
- def cookbook_path(self) -> Path:
- return PROMPTS_DIR / "glsl_shader" / "cookbook.md"
-
- # ------------------------------------------------------------------ skeleton / lint
- def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
- return write_skeleton(ws, plan)
-
- def lint(self, ws: Workspace) -> GateReport:
- return lint_workspace(ws)
-
- # ------------------------------------------------------------------ build
- def host(self, timeout_s: float | None = None) -> GlHost:
- return make_host(self._host, timeout_s)
-
- def compose_sources(self, ws: Workspace) -> tuple[Composed, Composed | None]:
- shader = (ws.root / SHADER).read_text(errors="replace")
- common_p = ws.root / COMMON
- common = common_p.read_text(errors="replace") if common_p.is_file() else None
- recipes_p = ws.root / RECIPES
- recipes = recipes_p.read_text(errors="replace") if recipes_p.is_file() else None
- image = compose(shader, common, recipes_src=recipes)
- buf_p = ws.root / BUFFER_A
- buffer_a = (compose(buf_p.read_text(errors="replace"), common, recipes_src=recipes, shader_file=BUFFER_A)
- if buf_p.is_file() else None)
- return image, buffer_a
-
- def build(self, ws: Workspace, *, timeout_s: int | None = None, times: list[float] | None = None,
- preview: bool = True, width: int | None = None, height: int | None = None) -> BuildResult:
- ws.artifacts.mkdir(parents=True, exist_ok=True)
- invalidate_stale_outputs(ws) # BEFORE the MissingEntry return, so it also clears
- if not (ws.root / SHADER).is_file():
- res = GlResult(ok=False, mode="shader", stage="lint", error_type="MissingEntry", error_message=f"{SHADER} is missing")
- return finish_build(ws, res, language=self.language.value, error_file=SHADER)
- plan = load_plan(ws)
- w, h = resolution_for(plan)
- if width and height:
- w, h = int(width), int(height)
- duration = plan.duration_s if plan else None
- image, buffer_a = self.compose_sources(ws)
- host = self.host(timeout_s)
- res = host.render_fragment_shader(
- image.source, ws.artifacts, width=w, height=h, times=times or judge_times(duration),
- buffer_a_src=buffer_a.source if buffer_a else None, feedback=image.uses_feedback or buffer_a is not None,
- extra_times=preview_times(duration) if preview else (),
- )
- census = {"convention": image.convention, "has_common": (ws.root / COMMON).is_file(), "has_buffer_a": buffer_a is not None,
- "has_recipes": (ws.root / RECIPES).is_file(), "resolution": [w, h]}
- err_file, err_line, err_msg = "", None, None
- if not res.ok and res.stage in ("compile", "compile_buffer_a"):
- comp = buffer_a if res.stage == "compile_buffer_a" and buffer_a else image
- msgs = parse_glsl_log(res.error_message, comp.line_map)
- first = first_error(msgs)
- if first is not None:
- err_file, err_line = first.file, first.file_line
- listed = "\n".join(m.text() for m in msgs[:12]) or res.error_message.strip()
- err_msg = f"GLSL compile error ({'buffer_a' if res.stage == 'compile_buffer_a' else 'shader'}):\n{listed}"
- res.error_type = "GlslCompileError"
- motion_expected = bool(plan.motion.strip()) if plan else True
- return finish_build(ws, res, language=self.language.value, error_file=err_file, error_line=err_line,
- error_message=err_msg, census=census, motion_expected=motion_expected)
diff --git a/harness/codeverse/languages/glsl_shader/skeleton.py b/harness/codeverse/languages/glsl_shader/skeleton.py
deleted file mode 100644
index aabd3f2c..00000000
--- a/harness/codeverse/languages/glsl_shader/skeleton.py
+++ /dev/null
@@ -1,108 +0,0 @@
-"""Skeleton for the glsl_shader language: a RUNNABLE starter pair
-(``src/common.glsl`` helpers + ``src/shader.frag`` entry) carrying the plan's
-passes / key visuals / motion as TODO comments and the uniform contract as a
-header comment. The baseline generator rewrites it; the harness can already
-build and render it (gradient sky + fbm haze + moving sun)."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from codeverse.contracts.plan import GraphicsPlan, Plan
-from codeverse.workspace import Workspace
-
-COMMON_GLSL = """// src/common.glsl — helpers pasted above shader.frag by the harness (no #include needed).
-// Keep ONLY functions / constants here; no main(), no uniforms, no #version.
-#define PI 3.14159265359
-#define TAU 6.28318530718
-
-float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); }
-float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
-vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
-
-// value noise 2D (smooth, 0..1)
-float noise(vec2 p) {
- vec2 i = floor(p), f = fract(p);
- vec2 u = f * f * (3.0 - 2.0 * f);
- return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x),
- mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
-}
-
-// fractal brownian motion, 5 octaves (constant loop bound)
-float fbm(vec2 p) {
- float v = 0.0, a = 0.5;
- mat2 rot = mat2(0.8, 0.6, -0.6, 0.8);
- for (int i = 0; i < 5; i++) { v += a * noise(p); p = rot * p * 2.02; a *= 0.5; }
- return v;
-}
-
-mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }
-
-// cosine palette (IQ): t in 0..1
-vec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) { return a + b * cos(TAU * (c * t + d)); }
-
-// filmic-ish tonemap + gamma
-vec3 tonemap(vec3 c) { c = c / (1.0 + c); return pow(clamp(c, 0.0, 1.0), vec3(1.0 / 2.2)); }
-"""
-
-_SHADER_TEMPLATE = """// src/shader.frag — {title}
-// CONTRACT (the harness prepends `#version 330 core` + these uniforms + `out vec4 fragColor`; DO NOT redeclare them):
-// uniform float u_time; uniform vec2 u_resolution; uniform vec2 u_mouse; uniform int u_frame;
-// uniform sampler2D u_prev; (previous frame of this pass) uniform sampler2D u_noise; (256x256 RGBA noise, repeat)
-// uniform sampler2D u_buffer_a; (output of src/buffer_a.frag when that file exists)
-// iTime / iResolution / iFrame / iMouse / iChannel0(=u_prev) / iChannel1(=u_noise) are #defined for Shadertoy ports.
-// Entry: void mainImage(out vec4 fragColor, in vec2 fragCoord) — fragCoord in pixels, origin BOTTOM-LEFT.
-// Helpers available from src/common.glsl: hash11 hash12 hash22 noise fbm rot2 palette tonemap PI TAU.
-// Duration {duration:g}s; judged frames at t = 0, 1, 2.5, 4, 6 s. Everything must MOVE with u_time.
-//
-// PLAN — {summary}
-// Style: {style}
-{passes}
-{visuals}
-// Motion: {motion}
-
-void mainImage(out vec4 fragColor, in vec2 fragCoord) {{
- vec2 uv = fragCoord / u_resolution.xy; // 0..1
- vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // aspect-correct, centred
- float t = u_time;
-
- // TODO replace this placeholder look with the plan's passes above
- vec3 sky = mix(vec3(0.95, 0.55, 0.25), vec3(0.10, 0.20, 0.45), smoothstep(-0.2, 0.6, p.y));
- vec2 sunPos = vec2(0.35 * cos(t * 0.3), 0.15 + 0.1 * sin(t * 0.3));
- float sun = exp(-40.0 * length(p - sunPos));
- float haze = fbm(p * 3.0 + vec2(t * 0.15, 0.0));
- vec3 col = sky + vec3(1.0, 0.8, 0.5) * sun + 0.25 * haze * vec3(0.9, 0.7, 0.6);
- col *= 1.0 - 0.35 * length(p); // vignette
- fragColor = vec4(tonemap(col), 1.0);
-}}
-"""
-
-
-def _comment_lines(prefix: str, items: list[str]) -> str:
- if not items:
- return f"// {prefix}: (none)"
- return "\n".join(f"// TODO {prefix} {i + 1}: {x}" for i, x in enumerate(items))
-
-
-def shader_source(plan: GraphicsPlan | None) -> str:
- title = plan.title if plan else "untitled shader"
- summary = plan.summary if plan else ""
- style = plan.style if plan else ""
- motion = plan.motion if plan else "animate with u_time"
- duration = plan.duration_s if plan else 8.0
- passes = [f"{p.name} ({p.kind}): {p.description}" for p in plan.passes] if plan else []
- visuals = list(plan.key_visuals) if plan else []
- return _SHADER_TEMPLATE.format(
- title=title, summary=summary, style=style, motion=motion, duration=duration,
- passes=_comment_lines("pass", passes), visuals=_comment_lines("key visual", visuals),
- )
-
-
-def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
- gplan = plan if isinstance(plan, GraphicsPlan) else None
- ws.src.mkdir(parents=True, exist_ok=True)
- common = ws.src / "common.glsl"
- shader = ws.src / "shader.frag"
- common.write_text(COMMON_GLSL)
- shader.write_text(shader_source(gplan))
- return [common, shader]
diff --git a/harness/codeverse/languages/glsl_shader/wrap.py b/harness/codeverse/languages/glsl_shader/wrap.py
deleted file mode 100644
index f2a27f11..00000000
--- a/harness/codeverse/languages/glsl_shader/wrap.py
+++ /dev/null
@@ -1,126 +0,0 @@
-"""Wrap an agent's Shadertoy-style fragment shader into a compilable GLSL 330 program.
-
-The harness owns the ``#version`` line, the uniform block and the ``main``
-trampoline; the agent writes only the body (``mainImage(out vec4 fragColor,
-in vec2 fragCoord)`` or a plain ``main()`` writing the harness-declared ``fragColor``).
-``compose`` pastes harness header < ``src/recipes.glsl`` (harness-owned seeded
-recipes, when present) < ``src/common.glsl`` < ``src/shader.frag`` (+ trailer) and
-returns the full source plus a :class:`LineMap` so compiler messages
-(``0:LINE(COL)`` / ``0(LINE)`` / ``ERROR: 0:LINE:`` variants) map back to
-``src/shader.frag`` / ``src/common.glsl`` / ``src/recipes.glsl`` line numbers.
-"""
-
-from __future__ import annotations
-
-import re
-from dataclasses import dataclass
-
-from codeverse.languages._gl_common import ( # noqa: F401 — re-exported
- GlslMessage,
- LineMap,
- Segment,
- parse_glsl_log,
-)
-
-UNIFORM_NAMES: tuple[str, ...] = ("u_time", "u_resolution", "u_mouse", "u_frame", "u_prev", "u_noise", "u_buffer_a")
-
-HEADER = """#version 330 core
-// ---- harness header (do not write these lines yourself) ----
-uniform float u_time; // seconds
-uniform vec2 u_resolution; // pixels
-uniform vec2 u_mouse; // pixels (always 0,0 headless)
-uniform int u_frame; // frame counter
-uniform sampler2D u_prev; // previous frame of THIS pass (feedback)
-uniform sampler2D u_noise; // 256x256 RGBA white noise, repeat, linear
-uniform sampler2D u_buffer_a;// output of src/buffer_a.frag (when present)
-#define iTime u_time
-#define iResolution vec3(u_resolution, 1.0)
-#define iFrame u_frame
-#define iMouse vec4(u_mouse, 0.0, 0.0)
-#define iTimeDelta (1.0/30.0)
-#define iChannel0 u_prev
-#define iChannel1 u_noise
-out vec4 fragColor; // the ONLY output; write it in mainImage()/main()
-"""
-
-MAIN_IMAGE_TRAILER = """
-// ---- harness trailer ----
-void main() { mainImage(fragColor, gl_FragCoord.xy); }
-"""
-
-_BLOCK_COMMENT = re.compile(r"/\*.*?\*/", re.S)
-_LINE_COMMENT = re.compile(r"//[^\n]*")
-_MAIN_IMAGE = re.compile(r"\bvoid\s+mainImage\s*\(")
-_PLAIN_MAIN = re.compile(r"\bvoid\s+main\s*\(\s*(void)?\s*\)")
-_OUT_DECL = re.compile(r"\bout\s+vec4\s+\w+\s*;")
-
-
-@dataclass
-class Composed:
- source: str
- line_map: LineMap
- convention: str # "mainImage" | "main"
- uses_feedback: bool
-
-
-def strip_comments(text: str) -> str:
- """Blank out comments but keep every newline so line numbers stay valid."""
- def _blank(m: re.Match[str]) -> str:
- return re.sub(r"[^\n]", " ", m.group(0))
-
- return _LINE_COMMENT.sub(_blank, _BLOCK_COMMENT.sub(_blank, text))
-
-
-def detect_convention(shader_src: str) -> str:
- shader_src = strip_comments(shader_src)
- if _MAIN_IMAGE.search(shader_src):
- return "mainImage"
- if _PLAIN_MAIN.search(shader_src):
- return "main"
- return "mainImage" # trailer will surface "mainImage undeclared" at compile time → clear error
-
-
-def _count(text: str) -> int:
- return text.count("\n") + (0 if text.endswith("\n") else 1)
-
-
-def _piece(text: str) -> str:
- return text if text.endswith("\n") else text + "\n"
-
-
-def compose(shader_src: str, common_src: str | None = None, *, recipes_src: str | None = None,
- shader_file: str = "src/shader.frag", common_file: str = "src/common.glsl",
- recipes_file: str = "src/recipes.glsl") -> Composed:
- """Header + recipes (harness-owned, first: self-contained, nothing in common.glsl can shadow it)
- + common + shader (+ trailer) with a line map back to the agent files."""
- convention = detect_convention(shader_src)
- pieces: list[tuple[str, str]] = [("harness", HEADER)]
- if recipes_src and recipes_src.strip():
- pieces.append((recipes_file, _piece(recipes_src)))
- if common_src and common_src.strip():
- pieces.append((common_file, _piece(common_src)))
- pieces.append((shader_file, _piece(shader_src)))
- if convention == "mainImage":
- pieces.append(("harness", MAIN_IMAGE_TRAILER))
- segments: list[Segment] = []
- cursor = 1
- out: list[str] = []
- for name, text in pieces:
- n = _count(text)
- segments.append(Segment(name, cursor, n))
- cursor += n
- out.append(text)
- src = "".join(out)
- code = strip_comments(shader_src) + "\n" + strip_comments(common_src or "") + "\n" + strip_comments(recipes_src or "")
- uses_feedback = "u_prev" in code or "iChannel0" in code
- return Composed(source=src, line_map=LineMap(segments), convention=convention, uses_feedback=uses_feedback)
-
-
-# --------------------------------------------------------------------------- compiler messages
-# GlslMessage / LineMap / parse_glsl_log live in ``_gl_common`` (shared with opengl_python)
-# and are re-exported above; only source composition + first_error remain here.
-def first_error(messages: list[GlslMessage]) -> GlslMessage | None:
- for m in messages:
- if m.kind == "error":
- return m
- return None
diff --git a/harness/codeverse/languages/opengl_python/__init__.py b/harness/codeverse/languages/opengl_python/__init__.py
index 67eb7eb8..329dedb9 100644
--- a/harness/codeverse/languages/opengl_python/__init__.py
+++ b/harness/codeverse/languages/opengl_python/__init__.py
@@ -1,5 +1,403 @@
"""opengl_python language: raw OpenGL (moderngl) programs rendered headless by the harness."""
-from codeverse.languages.opengl_python.runtime import OpenGLPythonRuntime
+from __future__ import annotations
-__all__ = ["OpenGLPythonRuntime"]
+import ast
+import re
+from pathlib import Path
+
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.plan import GraphicsPlan, Plan
+from codeverse.languages._ast_lint import (
+ BASE_FORBIDDEN_IMPORTS,
+ check_imports,
+ describe_parse_failure,
+ safe_parse,
+)
+from codeverse.languages._gl_common import (
+ finish_build,
+ invalidate_stale_outputs,
+ judge_times,
+ load_plan,
+ make_host,
+ parse_glsl_log,
+ preview_times,
+ resolution_for,
+ traceback_location,
+)
+from codeverse.prompts import PROMPTS_DIR, load_text
+from codeverse.spatial.gl_render import GlHost, GlResult
+from codeverse.workspace import Workspace
+
+# ===================================================================== lint
+# (merged from codeverse/languages/opengl_python/lint.py, 2026-08-28)
+GATE = "lint:opengl_python"
+PROGRAM = "src/program.py"
+ALLOWED_MODULES: frozenset[str] = frozenset({
+ "moderngl", "numpy", "math", "random", "struct", "array", "pathlib", "typing", "dataclasses", "itertools",
+ "functools", "collections", "colorsys", "__future__", "enum",
+})
+WINDOW_LIBS = {"glfw", "pygame", "pyglet", "PyQt5", "PyQt6", "PySide2", "PySide6", "tkinter", "moderngl_window", "sdl2", "wx", "OpenGL"}
+DANGEROUS_MODULES = frozenset(BASE_FORBIDDEN_IMPORTS | {
+ "os", "sys", # no interpreter / file-system access
+ "signal", "tempfile", "io", "time", "datetime", # frames must be a pure, deterministic function of t
+})
+FORBIDDEN_CALLS = {"open", "exec", "eval", "compile", "__import__", "input", "exit", "quit", "breakpoint"}
+MAX_CHARS = 120_000
+_VERSION_RE = re.compile(r"#\s*version\s+(\d+)(?:\s+(\w+))?")
+
+
+def _finding(sev: Severity, kind: str, msg: str, hint: str, line: int | None = None) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=PROGRAM, message=(f"{PROGRAM}:{line}: " if line else f"{PROGRAM}: ") + msg,
+ fix_hint=hint, data={"kind": kind, "line": line, "file": PROGRAM})
+
+
+def _root(name: str) -> str:
+ return name.split(".", 1)[0]
+
+
+class _Visitor(ast.NodeVisitor):
+ def __init__(self) -> None:
+ self.findings: list[GateFinding] = []
+ self.funcs: dict[str, ast.FunctionDef] = {}
+ self.seeded = False
+ self.uses_random = False
+
+ # imports -------------------------------------------------------------
+ def _check_module(self, name: str, line: int) -> None:
+ root = _root(name)
+ if root in WINDOW_LIBS:
+ self.findings.append(_finding(Severity.ERROR, "window_lib", f"imports `{name}` (window / input library)",
+ "the harness creates the context and framebuffer; draw into the fbo it passes — no window", line))
+ return
+
+ def _import_finding(kind: str, _mod: str, ln: int) -> GateFinding:
+ if kind == "forbidden":
+ return _finding(Severity.ERROR, "forbidden_import", f"imports `{name}` (not allowed in a rendering program)",
+ "allowed: moderngl, numpy, math, random, struct, array, pathlib, typing, dataclasses, itertools, "
+ "functools, collections, colorsys", ln)
+ return _finding(Severity.ERROR, "forbidden_import", f"imports `{name}` which is outside the allow-list",
+ "use only moderngl + numpy + stdlib math/random/struct/array/pathlib", ln)
+
+ self.findings.extend(check_imports({root: line}, forbidden=DANGEROUS_MODULES, allowed=ALLOWED_MODULES,
+ make_finding=_import_finding))
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ self._check_module(a.name, node.lineno)
+ self.generic_visit(node)
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ if node.module:
+ self._check_module(node.module, node.lineno)
+ self.generic_visit(node)
+
+ # calls ---------------------------------------------------------------
+ def visit_Call(self, node: ast.Call) -> None:
+ fn = node.func
+ name = fn.id if isinstance(fn, ast.Name) else None
+ attr = fn.attr if isinstance(fn, ast.Attribute) else None
+ base = fn.value.id if isinstance(fn, ast.Attribute) and isinstance(fn.value, ast.Name) else None
+ if name in FORBIDDEN_CALLS:
+ self.findings.append(_finding(Severity.ERROR, "forbidden_call", f"calls `{name}()`",
+ "no file/console IO: put GLSL in triple-quoted strings, or Path(__file__).with_name('x.glsl').read_text()",
+ node.lineno))
+ if attr in ("create_context", "create_standalone_context") and base == "moderngl":
+ self.findings.append(_finding(Severity.ERROR, "own_context", "creates its own moderngl context",
+ "use the `ctx` passed to setup()/render(); never create a context or window", node.lineno))
+ if base == "time" and attr in ("time", "perf_counter", "monotonic"):
+ self.findings.append(_finding(Severity.ERROR, "wall_clock", "reads the wall clock", "use the `t` argument of render(); frames must be a pure function of t", node.lineno))
+ if base == "random" and attr == "seed":
+ self.seeded = True
+ if base == "random" and attr in ("random", "uniform", "randint", "gauss", "choice", "shuffle"):
+ self.uses_random = True
+ if base in ("np", "numpy") and attr == "seed":
+ self.seeded = True
+ if attr in ("write_text", "write_bytes", "unlink", "mkdir", "rmdir", "rename"):
+ self.findings.append(_finding(Severity.ERROR, "file_write", f"calls `.{attr}()` (file system write)", "programs never write files", node.lineno))
+ if attr == "read_text" or attr == "read_bytes":
+ self.findings.append(_finding(Severity.INFO, "read_file", f"reads a file via `.{attr}()` — only src/*.glsl shipped next to program.py is allowed",
+ "Path(__file__).with_name('x.glsl').read_text()", node.lineno))
+ self.generic_visit(node)
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ self.funcs[node.name] = node
+ self.generic_visit(node)
+
+ def visit_Constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, str) and "#version" in node.value:
+ m = _VERSION_RE.search(node.value)
+ if m and (m.group(1) != "330" or (m.group(2) or "core") != "core"):
+ self.findings.append(_finding(Severity.WARN, "glsl_version", f"GLSL string uses `#version {m.group(1)} {m.group(2) or ''}`; the context is GL 3.3 core",
+ "use `#version 330 core` in every shader string", node.lineno))
+ if isinstance(node.value, str) and "gl_FragColor" in node.value:
+ self.findings.append(_finding(Severity.ERROR, "legacy_glsl", "GLSL string uses gl_FragColor (GLSL 1.x)",
+ "declare `out vec4 fragColor;` and write it (GLSL 330 core)", node.lineno))
+ if isinstance(node.value, str) and ("attribute " in node.value or "varying " in node.value) and "#version" in node.value:
+ self.findings.append(_finding(Severity.ERROR, "legacy_glsl", "GLSL string uses attribute/varying (GLSL 1.x)",
+ "use `in` / `out` qualifiers (GLSL 330 core)", node.lineno))
+
+
+def lint_source(text: str) -> list[GateFinding]:
+ findings: list[GateFinding] = []
+ if len(text) > MAX_CHARS:
+ findings.append(_finding(Severity.WARN, "too_long", f"file is {len(text)} chars", "keep the program focused"))
+ tree, exc = safe_parse(text)
+ if tree is None:
+ msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
+ findings.append(_finding(Severity.ERROR, "syntax", msg, hint if not isinstance(exc, SyntaxError) else "fix the syntax at this line", line))
+ return findings
+ v = _Visitor()
+ v.visit(tree)
+ findings.extend(v.findings)
+ for fn, nargs in (("setup", 3), ("render", 5)):
+ node = v.funcs.get(fn)
+ if node is None:
+ findings.append(_finding(Severity.ERROR, "missing_entry", f"missing `def {fn}(...)`",
+ "def setup(ctx, width, height) -> state and def render(ctx, state, t, frame, fbo) -> None"))
+ elif len(node.args.args) != nargs and node.args.vararg is None:
+ findings.append(_finding(Severity.ERROR, "bad_signature", f"`{fn}` takes {len(node.args.args)} positional args, expected {nargs}",
+ "setup(ctx, width, height) / render(ctx, state, t, frame, fbo)", node.lineno))
+ if v.uses_random and not v.seeded:
+ findings.append(_finding(Severity.WARN, "unseeded_random", "uses random.* without random.seed(...)",
+ "call random.seed(0) / np.random.default_rng(0) in setup() so frames are reproducible"))
+ return findings
+
+
+def lint_workspace(ws: Workspace) -> GateReport:
+ p = ws.root / PROGRAM
+ if not p.is_file():
+ f = [_finding(Severity.ERROR, "missing_entry", f"{PROGRAM} is missing",
+ "create src/program.py with setup(ctx, width, height) and render(ctx, state, t, frame, fbo)")]
+ return GateReport(gate=GATE, passed=False, findings=f)
+ findings = lint_source(p.read_text(errors="replace"))
+ for extra in sorted(ws.src.rglob("*.py")):
+ rel = str(extra.relative_to(ws.root))
+ if rel != PROGRAM:
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel}: extra python module is ignored by the harness",
+ fix_hint="keep all code in src/program.py (GLSL may live in src/*.glsl)", data={"kind": "stray_file", "file": rel}))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings)
+
+
+# ===================================================================== skeleton
+# (merged from codeverse/languages/opengl_python/skeleton.py, 2026-08-28)
+_TEMPLATE = '''"""src/program.py — {title}
+
+CONTRACT (the harness imports this module in a headless moderngl process):
+ def setup(ctx, width, height) -> state create programs / VAOs / textures / FBOs ONCE; return any object
+ def render(ctx, state, t, frame, fbo) draw the frame at time t (seconds) into `fbo` (already bound + cleared)
+* `ctx` is a moderngl.Context (GL 3.3 core). Never create a context or window; never read the clock.
+* Multi-pass: render into your own FBOs, then call `fbo.use()` and draw the final image into it.
+* Deterministic: same t → same frame. Seed randomness. GLSL strings use `#version 330 core`.
+* Allowed imports: moderngl, numpy, math, random, struct, array, pathlib (+typing/dataclasses).
+Duration {duration:g}s; judged frames at t = 0, 1, 2.5, 4, 6 s — everything must MOVE with t.
+
+PLAN — {summary}
+Style: {style}
+{passes}
+{visuals}
+Motion: {motion}
+"""
+import math
+
+import moderngl
+import numpy as np
+
+BACKGROUND_VERT = """#version 330 core
+in vec2 in_pos;
+out vec2 v_uv;
+void main() {{ v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }}
+"""
+BACKGROUND_FRAG = """#version 330 core
+uniform float u_time;
+in vec2 v_uv;
+out vec4 fragColor;
+void main() {{
+ vec3 top = vec3(0.08, 0.10, 0.25), bottom = vec3(0.85, 0.45, 0.30);
+ vec3 col = mix(bottom, top, smoothstep(0.0, 1.0, v_uv.y + 0.1 * sin(u_time * 0.5 + v_uv.x * 6.0)));
+ fragColor = vec4(col, 1.0);
+}}
+"""
+CUBE_VERT = """#version 330 core
+uniform mat4 u_mvp;
+uniform mat4 u_model;
+in vec3 in_pos;
+in vec3 in_normal;
+out vec3 v_normal;
+void main() {{ v_normal = mat3(u_model) * in_normal; gl_Position = u_mvp * vec4(in_pos, 1.0); }}
+"""
+CUBE_FRAG = """#version 330 core
+uniform vec3 u_color;
+in vec3 v_normal;
+out vec4 fragColor;
+void main() {{
+ vec3 n = normalize(v_normal);
+ float diff = max(dot(n, normalize(vec3(0.4, 0.8, 0.5))), 0.0);
+ fragColor = vec4(u_color * (0.25 + 0.75 * diff), 1.0);
+}}
+"""
+
+
+def _cube() -> np.ndarray:
+ """36 vertices: position (3) + normal (3), interleaved float32."""
+ faces = [((0, 0, 1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)),
+ ((0, 0, -1), (1, -1, -1), (-1, -1, -1), (-1, 1, -1), (1, 1, -1)),
+ ((1, 0, 0), (1, -1, 1), (1, -1, -1), (1, 1, -1), (1, 1, 1)),
+ ((-1, 0, 0), (-1, -1, -1), (-1, -1, 1), (-1, 1, 1), (-1, 1, -1)),
+ ((0, 1, 0), (-1, 1, 1), (1, 1, 1), (1, 1, -1), (-1, 1, -1)),
+ ((0, -1, 0), (-1, -1, -1), (1, -1, -1), (1, -1, 1), (-1, -1, 1))]
+ out = []
+ for n, a, b, c, d in faces:
+ for v in (a, b, c, a, c, d):
+ out.extend(v)
+ out.extend(n)
+ return np.array(out, dtype="f4") * np.tile([0.5, 0.5, 0.5, 1, 1, 1], 36).astype("f4")
+
+
+def _perspective(fov_deg: float, aspect: float, near: float, far: float) -> np.ndarray:
+ f = 1.0 / math.tan(math.radians(fov_deg) / 2.0)
+ m = np.zeros((4, 4), dtype="f4")
+ m[0, 0], m[1, 1] = f / aspect, f
+ m[2, 2], m[2, 3] = (far + near) / (near - far), (2 * far * near) / (near - far)
+ m[3, 2] = -1.0
+ return m
+
+
+def _look_at(eye, target, up=(0, 1, 0)) -> np.ndarray:
+ eye, target, up = np.array(eye, dtype="f4"), np.array(target, dtype="f4"), np.array(up, dtype="f4")
+ f = target - eye
+ f /= np.linalg.norm(f)
+ s = np.cross(f, up)
+ s /= np.linalg.norm(s)
+ u = np.cross(s, f)
+ m = np.identity(4, dtype="f4")
+ m[0, :3], m[1, :3], m[2, :3] = s, u, -f
+ m[:3, 3] = -m[:3, :3] @ eye
+ return m
+
+
+def _rot_y(a: float) -> np.ndarray:
+ c, s = math.cos(a), math.sin(a)
+ return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype="f4")
+
+
+def setup(ctx: moderngl.Context, width: int, height: int):
+ bg_prog = ctx.program(vertex_shader=BACKGROUND_VERT, fragment_shader=BACKGROUND_FRAG)
+ quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
+ bg_vao = ctx.vertex_array(bg_prog, [(quad, "2f", "in_pos")])
+ cube_prog = ctx.program(vertex_shader=CUBE_VERT, fragment_shader=CUBE_FRAG)
+ vbo = ctx.buffer(_cube().tobytes())
+ cube_vao = ctx.vertex_array(cube_prog, [(vbo, "3f 3f", "in_pos", "in_normal")])
+ proj = _perspective(45.0, width / height, 0.1, 100.0)
+ view = _look_at((0.0, 1.2, 3.0), (0.0, 0.0, 0.0))
+ # TODO build the plan's passes here (instancing, extra FBOs for post-processing, textures)
+ return {{"bg_prog": bg_prog, "bg_vao": bg_vao, "cube_prog": cube_prog, "cube_vao": cube_vao, "proj": proj, "view": view}}
+
+
+def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
+ fbo.use()
+ ctx.disable(moderngl.DEPTH_TEST)
+ state["bg_prog"]["u_time"].value = t
+ state["bg_vao"].render(mode=moderngl.TRIANGLE_STRIP)
+ ctx.enable(moderngl.DEPTH_TEST)
+ model = _rot_y(t * 0.8)
+ mvp = state["proj"] @ state["view"] @ model
+ state["cube_prog"]["u_mvp"].write(mvp.T.astype("f4").tobytes()) # column-major for GLSL
+ state["cube_prog"]["u_model"].write(model.T.astype("f4").tobytes())
+ state["cube_prog"]["u_color"].value = (0.9, 0.6, 0.2)
+ state["cube_vao"].render(mode=moderngl.TRIANGLES)
+ # TODO replace the placeholder cube with the plan's content; keep drawing into `fbo` last
+'''
+
+
+def _comment_lines(prefix: str, items: list[str]) -> str:
+ if not items:
+ return f"{prefix}: (none)"
+ return "\n".join(f" TODO {prefix} {i + 1}: {x}" for i, x in enumerate(items))
+
+
+def program_source(plan: GraphicsPlan | None) -> str:
+ title = plan.title if plan else "untitled program"
+ passes = [f"{p.name} ({p.kind}): {p.description}" for p in plan.passes] if plan else []
+ visuals = list(plan.key_visuals) if plan else []
+ return _TEMPLATE.format(
+ title=title, summary=plan.summary if plan else "", style=plan.style if plan else "",
+ motion=plan.motion if plan else "animate with t", duration=plan.duration_s if plan else 8.0,
+ passes=_comment_lines("pass", passes), visuals=_comment_lines("key visual", visuals),
+ )
+
+
+def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
+ gplan = plan if isinstance(plan, GraphicsPlan) else None
+ ws.src.mkdir(parents=True, exist_ok=True)
+ p = ws.src / "program.py"
+ p.write_text(program_source(gplan))
+ return [p]
+
+
+# ===================================================================== runtime
+# (merged from codeverse/languages/opengl_python/runtime.py, 2026-08-28)
+CONTRACT_FALLBACK = """src/program.py — raw moderngl program: `def setup(ctx, width, height) -> state` (programs, VAOs, textures,
+FBOs; GLSL 330 core inline strings) and `def render(ctx, state, t, frame, fbo)` (draw the frame at time t into the given,
+already bound framebuffer; multi-pass via your own FBOs, finish with fbo.use()). No window, no context creation, no clock,
+no file IO (except src/*.glsl next to program.py). Imports: moderngl, numpy, math, random, struct, array, pathlib."""
+
+
+class OpenGLPythonRuntime:
+ language = Language.OPENGL_PYTHON
+ entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.OPENGL_PYTHON], "src/*.glsl")
+
+ def __init__(self, *, host: GlHost | None = None):
+ self._host = host
+
+ # ------------------------------------------------------------------ contract
+ def contract_doc(self) -> str:
+ try:
+ return load_text("opengl_python/contract.md")
+ except FileNotFoundError:
+ return CONTRACT_FALLBACK
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "opengl_python" / "cookbook.md"
+
+ # ------------------------------------------------------------------ skeleton / lint
+ def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ # ------------------------------------------------------------------ build
+ def host(self, timeout_s: float | None = None) -> GlHost:
+ return make_host(self._host, timeout_s)
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None, times: list[float] | None = None,
+ preview: bool = True, width: int | None = None, height: int | None = None) -> BuildResult:
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ invalidate_stale_outputs(ws) # BEFORE the MissingEntry return, so it also clears
+ program = ws.root / PROGRAM
+ if not program.is_file():
+ res = GlResult(ok=False, mode="program", stage="lint", error_type="MissingEntry", error_message=f"{PROGRAM} is missing")
+ return finish_build(ws, res, language=self.language.value, error_file=PROGRAM)
+ plan = load_plan(ws)
+ w, h = resolution_for(plan)
+ if width and height:
+ w, h = int(width), int(height)
+ duration = plan.duration_s if plan else None
+ res = self.host(timeout_s).run_program(program, ws.artifacts, width=w, height=h, times=times or judge_times(duration),
+ extra_times=preview_times(duration) if preview else (), cwd=ws.src)
+ err_file, err_line, err_msg = "", None, None
+ if not res.ok:
+ err_file, err_line = traceback_location(res.traceback, program)
+ err_msg = f"{res.stage} failed: {res.error_type}: {res.error_message}"
+ glsl = parse_glsl_log(res.error_message)
+ if glsl:
+ res.error_type = "GlslCompileError"
+ err_msg += "\n(GLSL line numbers refer to the shader STRING inside program.py: " + \
+ "; ".join(f"line {m.line}: {m.message}" for m in glsl[:8]) + ")"
+ census = {"resolution": [w, h]}
+ motion_expected = bool(plan.motion.strip()) if plan else True
+ return finish_build(ws, res, language=self.language.value, error_file=err_file, error_line=err_line,
+ error_message=err_msg, census=census, motion_expected=motion_expected)
diff --git a/harness/codeverse/languages/opengl_python/lint.py b/harness/codeverse/languages/opengl_python/lint.py
deleted file mode 100644
index 4031ad82..00000000
--- a/harness/codeverse/languages/opengl_python/lint.py
+++ /dev/null
@@ -1,175 +0,0 @@
-"""AST lint for ``src/program.py`` (raw moderngl program).
-
-Rules (gate ``lint:opengl_python``, ``data["kind"]`` names the rule):
-* syntax must parse; ``setup(ctx, width, height)`` and ``render(ctx, state, t, frame, fbo)`` must exist;
-* imports restricted to an allow-list (moderngl, numpy, math, random, struct, array, pathlib,
- typing, dataclasses, itertools, functools, collections, colorsys);
-* no window / input libs (glfw, pygame, pyglet, PyQt…), no os / sys / subprocess / socket / requests;
-* no ``open()`` / exec / eval / __import__ / compile (GLSL travels as inline strings or via
- ``Path(__file__).with_name("x.glsl").read_text()``);
-* no ``time.time()`` / ``datetime.now()`` / unseeded randomness (frames must be deterministic in ``t``);
-* ``moderngl.create_context`` / ``create_standalone_context`` inside the program (the harness owns the context);
-* GLSL strings in the file get a light ``#version`` check (must be ``330 core`` or absent → warn).
-"""
-
-from __future__ import annotations
-
-import ast
-import re
-
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.languages._ast_lint import (
- BASE_FORBIDDEN_IMPORTS,
- check_imports,
- describe_parse_failure,
- safe_parse,
-)
-from codeverse.workspace import Workspace
-
-GATE = "lint:opengl_python"
-PROGRAM = "src/program.py"
-ALLOWED_MODULES: frozenset[str] = frozenset({
- "moderngl", "numpy", "math", "random", "struct", "array", "pathlib", "typing", "dataclasses", "itertools",
- "functools", "collections", "colorsys", "__future__", "enum",
-})
-WINDOW_LIBS = {"glfw", "pygame", "pyglet", "PyQt5", "PyQt6", "PySide2", "PySide6", "tkinter", "moderngl_window", "sdl2", "wx", "OpenGL"}
-DANGEROUS_MODULES = frozenset(BASE_FORBIDDEN_IMPORTS | {
- "os", "sys", # no interpreter / file-system access
- "signal", "tempfile", "io", "time", "datetime", # frames must be a pure, deterministic function of t
-})
-FORBIDDEN_CALLS = {"open", "exec", "eval", "compile", "__import__", "input", "exit", "quit", "breakpoint"}
-MAX_CHARS = 120_000
-_VERSION_RE = re.compile(r"#\s*version\s+(\d+)(?:\s+(\w+))?")
-
-
-def _finding(sev: Severity, kind: str, msg: str, hint: str, line: int | None = None) -> GateFinding:
- return GateFinding(gate=GATE, severity=sev, target=PROGRAM, message=(f"{PROGRAM}:{line}: " if line else f"{PROGRAM}: ") + msg,
- fix_hint=hint, data={"kind": kind, "line": line, "file": PROGRAM})
-
-
-def _root(name: str) -> str:
- return name.split(".", 1)[0]
-
-
-class _Visitor(ast.NodeVisitor):
- def __init__(self) -> None:
- self.findings: list[GateFinding] = []
- self.funcs: dict[str, ast.FunctionDef] = {}
- self.seeded = False
- self.uses_random = False
-
- # imports -------------------------------------------------------------
- def _check_module(self, name: str, line: int) -> None:
- root = _root(name)
- if root in WINDOW_LIBS:
- self.findings.append(_finding(Severity.ERROR, "window_lib", f"imports `{name}` (window / input library)",
- "the harness creates the context and framebuffer; draw into the fbo it passes — no window", line))
- return
-
- def _import_finding(kind: str, _mod: str, ln: int) -> GateFinding:
- if kind == "forbidden":
- return _finding(Severity.ERROR, "forbidden_import", f"imports `{name}` (not allowed in a rendering program)",
- "allowed: moderngl, numpy, math, random, struct, array, pathlib, typing, dataclasses, itertools, "
- "functools, collections, colorsys", ln)
- return _finding(Severity.ERROR, "forbidden_import", f"imports `{name}` which is outside the allow-list",
- "use only moderngl + numpy + stdlib math/random/struct/array/pathlib", ln)
-
- self.findings.extend(check_imports({root: line}, forbidden=DANGEROUS_MODULES, allowed=ALLOWED_MODULES,
- make_finding=_import_finding))
-
- def visit_Import(self, node: ast.Import) -> None:
- for a in node.names:
- self._check_module(a.name, node.lineno)
- self.generic_visit(node)
-
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
- if node.module:
- self._check_module(node.module, node.lineno)
- self.generic_visit(node)
-
- # calls ---------------------------------------------------------------
- def visit_Call(self, node: ast.Call) -> None:
- fn = node.func
- name = fn.id if isinstance(fn, ast.Name) else None
- attr = fn.attr if isinstance(fn, ast.Attribute) else None
- base = fn.value.id if isinstance(fn, ast.Attribute) and isinstance(fn.value, ast.Name) else None
- if name in FORBIDDEN_CALLS:
- self.findings.append(_finding(Severity.ERROR, "forbidden_call", f"calls `{name}()`",
- "no file/console IO: put GLSL in triple-quoted strings, or Path(__file__).with_name('x.glsl').read_text()",
- node.lineno))
- if attr in ("create_context", "create_standalone_context") and base == "moderngl":
- self.findings.append(_finding(Severity.ERROR, "own_context", "creates its own moderngl context",
- "use the `ctx` passed to setup()/render(); never create a context or window", node.lineno))
- if base == "time" and attr in ("time", "perf_counter", "monotonic"):
- self.findings.append(_finding(Severity.ERROR, "wall_clock", "reads the wall clock", "use the `t` argument of render(); frames must be a pure function of t", node.lineno))
- if base == "random" and attr == "seed":
- self.seeded = True
- if base == "random" and attr in ("random", "uniform", "randint", "gauss", "choice", "shuffle"):
- self.uses_random = True
- if base in ("np", "numpy") and attr == "seed":
- self.seeded = True
- if attr in ("write_text", "write_bytes", "unlink", "mkdir", "rmdir", "rename"):
- self.findings.append(_finding(Severity.ERROR, "file_write", f"calls `.{attr}()` (file system write)", "programs never write files", node.lineno))
- if attr == "read_text" or attr == "read_bytes":
- self.findings.append(_finding(Severity.INFO, "read_file", f"reads a file via `.{attr}()` — only src/*.glsl shipped next to program.py is allowed",
- "Path(__file__).with_name('x.glsl').read_text()", node.lineno))
- self.generic_visit(node)
-
- def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
- self.funcs[node.name] = node
- self.generic_visit(node)
-
- def visit_Constant(self, node: ast.Constant) -> None:
- if isinstance(node.value, str) and "#version" in node.value:
- m = _VERSION_RE.search(node.value)
- if m and (m.group(1) != "330" or (m.group(2) or "core") != "core"):
- self.findings.append(_finding(Severity.WARN, "glsl_version", f"GLSL string uses `#version {m.group(1)} {m.group(2) or ''}`; the context is GL 3.3 core",
- "use `#version 330 core` in every shader string", node.lineno))
- if isinstance(node.value, str) and "gl_FragColor" in node.value:
- self.findings.append(_finding(Severity.ERROR, "legacy_glsl", "GLSL string uses gl_FragColor (GLSL 1.x)",
- "declare `out vec4 fragColor;` and write it (GLSL 330 core)", node.lineno))
- if isinstance(node.value, str) and ("attribute " in node.value or "varying " in node.value) and "#version" in node.value:
- self.findings.append(_finding(Severity.ERROR, "legacy_glsl", "GLSL string uses attribute/varying (GLSL 1.x)",
- "use `in` / `out` qualifiers (GLSL 330 core)", node.lineno))
-
-
-def lint_source(text: str) -> list[GateFinding]:
- findings: list[GateFinding] = []
- if len(text) > MAX_CHARS:
- findings.append(_finding(Severity.WARN, "too_long", f"file is {len(text)} chars", "keep the program focused"))
- tree, exc = safe_parse(text)
- if tree is None:
- msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
- findings.append(_finding(Severity.ERROR, "syntax", msg, hint if not isinstance(exc, SyntaxError) else "fix the syntax at this line", line))
- return findings
- v = _Visitor()
- v.visit(tree)
- findings.extend(v.findings)
- for fn, nargs in (("setup", 3), ("render", 5)):
- node = v.funcs.get(fn)
- if node is None:
- findings.append(_finding(Severity.ERROR, "missing_entry", f"missing `def {fn}(...)`",
- "def setup(ctx, width, height) -> state and def render(ctx, state, t, frame, fbo) -> None"))
- elif len(node.args.args) != nargs and node.args.vararg is None:
- findings.append(_finding(Severity.ERROR, "bad_signature", f"`{fn}` takes {len(node.args.args)} positional args, expected {nargs}",
- "setup(ctx, width, height) / render(ctx, state, t, frame, fbo)", node.lineno))
- if v.uses_random and not v.seeded:
- findings.append(_finding(Severity.WARN, "unseeded_random", "uses random.* without random.seed(...)",
- "call random.seed(0) / np.random.default_rng(0) in setup() so frames are reproducible"))
- return findings
-
-
-def lint_workspace(ws: Workspace) -> GateReport:
- p = ws.root / PROGRAM
- if not p.is_file():
- f = [_finding(Severity.ERROR, "missing_entry", f"{PROGRAM} is missing",
- "create src/program.py with setup(ctx, width, height) and render(ctx, state, t, frame, fbo)")]
- return GateReport(gate=GATE, passed=False, findings=f)
- findings = lint_source(p.read_text(errors="replace"))
- for extra in sorted(ws.src.rglob("*.py")):
- rel = str(extra.relative_to(ws.root))
- if rel != PROGRAM:
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel}: extra python module is ignored by the harness",
- fix_hint="keep all code in src/program.py (GLSL may live in src/*.glsl)", data={"kind": "stray_file", "file": rel}))
- passed = not any(f.severity == Severity.ERROR for f in findings)
- return GateReport(gate=GATE, passed=passed, findings=findings)
diff --git a/harness/codeverse/languages/opengl_python/runtime.py b/harness/codeverse/languages/opengl_python/runtime.py
deleted file mode 100644
index 5843714c..00000000
--- a/harness/codeverse/languages/opengl_python/runtime.py
+++ /dev/null
@@ -1,96 +0,0 @@
-"""OpenGLPythonRuntime: skeleton → AST lint → build (import + render frames in a moderngl subprocess).
-
-``src/program.py`` defines ``setup(ctx, width, height) -> state`` and
-``render(ctx, state, t, frame, fbo)``. The harness runner imports it by path
-(cwd = ``src/``), binds + clears a float RGBA framebuffer per frame, calls
-``render`` at the judged times, reads back (y-flipped) PNGs, detects NaN/Inf.
-Python exceptions are mapped to ``src/program.py:LINE``; GLSL compile errors
-inside the program surface as moderngl ``Error`` with the driver's info log.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from codeverse.contracts.artifacts import BuildResult, GateReport
-from codeverse.contracts.common import ENTRY_FILE, Language
-from codeverse.contracts.plan import Plan
-from codeverse.languages._gl_common import (
- finish_build,
- invalidate_stale_outputs,
- judge_times,
- load_plan,
- make_host,
- parse_glsl_log,
- preview_times,
- resolution_for,
- traceback_location,
-)
-from codeverse.languages.opengl_python.lint import PROGRAM, lint_workspace
-from codeverse.languages.opengl_python.skeleton import write_skeleton
-from codeverse.prompts import PROMPTS_DIR, load_text
-from codeverse.spatial.gl_render import GlHost, GlResult
-from codeverse.workspace import Workspace
-
-CONTRACT_FALLBACK = """src/program.py — raw moderngl program: `def setup(ctx, width, height) -> state` (programs, VAOs, textures,
-FBOs; GLSL 330 core inline strings) and `def render(ctx, state, t, frame, fbo)` (draw the frame at time t into the given,
-already bound framebuffer; multi-pass via your own FBOs, finish with fbo.use()). No window, no context creation, no clock,
-no file IO (except src/*.glsl next to program.py). Imports: moderngl, numpy, math, random, struct, array, pathlib."""
-
-
-class OpenGLPythonRuntime:
- language = Language.OPENGL_PYTHON
- entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.OPENGL_PYTHON], "src/*.glsl")
-
- def __init__(self, *, host: GlHost | None = None):
- self._host = host
-
- # ------------------------------------------------------------------ contract
- def contract_doc(self) -> str:
- try:
- return load_text("opengl_python/contract.md")
- except FileNotFoundError:
- return CONTRACT_FALLBACK
-
- def cookbook_path(self) -> Path:
- return PROMPTS_DIR / "opengl_python" / "cookbook.md"
-
- # ------------------------------------------------------------------ skeleton / lint
- def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
- return write_skeleton(ws, plan)
-
- def lint(self, ws: Workspace) -> GateReport:
- return lint_workspace(ws)
-
- # ------------------------------------------------------------------ build
- def host(self, timeout_s: float | None = None) -> GlHost:
- return make_host(self._host, timeout_s)
-
- def build(self, ws: Workspace, *, timeout_s: int | None = None, times: list[float] | None = None,
- preview: bool = True, width: int | None = None, height: int | None = None) -> BuildResult:
- ws.artifacts.mkdir(parents=True, exist_ok=True)
- invalidate_stale_outputs(ws) # BEFORE the MissingEntry return, so it also clears
- program = ws.root / PROGRAM
- if not program.is_file():
- res = GlResult(ok=False, mode="program", stage="lint", error_type="MissingEntry", error_message=f"{PROGRAM} is missing")
- return finish_build(ws, res, language=self.language.value, error_file=PROGRAM)
- plan = load_plan(ws)
- w, h = resolution_for(plan)
- if width and height:
- w, h = int(width), int(height)
- duration = plan.duration_s if plan else None
- res = self.host(timeout_s).run_program(program, ws.artifacts, width=w, height=h, times=times or judge_times(duration),
- extra_times=preview_times(duration) if preview else (), cwd=ws.src)
- err_file, err_line, err_msg = "", None, None
- if not res.ok:
- err_file, err_line = traceback_location(res.traceback, program)
- err_msg = f"{res.stage} failed: {res.error_type}: {res.error_message}"
- glsl = parse_glsl_log(res.error_message)
- if glsl:
- res.error_type = "GlslCompileError"
- err_msg += "\n(GLSL line numbers refer to the shader STRING inside program.py: " + \
- "; ".join(f"line {m.line}: {m.message}" for m in glsl[:8]) + ")"
- census = {"resolution": [w, h]}
- motion_expected = bool(plan.motion.strip()) if plan else True
- return finish_build(ws, res, language=self.language.value, error_file=err_file, error_line=err_line,
- error_message=err_msg, census=census, motion_expected=motion_expected)
diff --git a/harness/codeverse/languages/opengl_python/skeleton.py b/harness/codeverse/languages/opengl_python/skeleton.py
deleted file mode 100644
index b4b7ccae..00000000
--- a/harness/codeverse/languages/opengl_python/skeleton.py
+++ /dev/null
@@ -1,164 +0,0 @@
-"""Skeleton for the opengl_python language: a RUNNABLE ``src/program.py`` (background
-gradient pass + one rotating lit cube) that shows the exact API the harness calls —
-``setup(ctx, width, height) -> state`` and ``render(ctx, state, t, frame, fbo)`` —
-with the plan's passes / key visuals / motion as TODO comments."""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from codeverse.contracts.plan import GraphicsPlan, Plan
-from codeverse.workspace import Workspace
-
-_TEMPLATE = '''"""src/program.py — {title}
-
-CONTRACT (the harness imports this module in a headless moderngl process):
- def setup(ctx, width, height) -> state create programs / VAOs / textures / FBOs ONCE; return any object
- def render(ctx, state, t, frame, fbo) draw the frame at time t (seconds) into `fbo` (already bound + cleared)
-* `ctx` is a moderngl.Context (GL 3.3 core). Never create a context or window; never read the clock.
-* Multi-pass: render into your own FBOs, then call `fbo.use()` and draw the final image into it.
-* Deterministic: same t → same frame. Seed randomness. GLSL strings use `#version 330 core`.
-* Allowed imports: moderngl, numpy, math, random, struct, array, pathlib (+typing/dataclasses).
-Duration {duration:g}s; judged frames at t = 0, 1, 2.5, 4, 6 s — everything must MOVE with t.
-
-PLAN — {summary}
-Style: {style}
-{passes}
-{visuals}
-Motion: {motion}
-"""
-import math
-
-import moderngl
-import numpy as np
-
-BACKGROUND_VERT = """#version 330 core
-in vec2 in_pos;
-out vec2 v_uv;
-void main() {{ v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }}
-"""
-BACKGROUND_FRAG = """#version 330 core
-uniform float u_time;
-in vec2 v_uv;
-out vec4 fragColor;
-void main() {{
- vec3 top = vec3(0.08, 0.10, 0.25), bottom = vec3(0.85, 0.45, 0.30);
- vec3 col = mix(bottom, top, smoothstep(0.0, 1.0, v_uv.y + 0.1 * sin(u_time * 0.5 + v_uv.x * 6.0)));
- fragColor = vec4(col, 1.0);
-}}
-"""
-CUBE_VERT = """#version 330 core
-uniform mat4 u_mvp;
-uniform mat4 u_model;
-in vec3 in_pos;
-in vec3 in_normal;
-out vec3 v_normal;
-void main() {{ v_normal = mat3(u_model) * in_normal; gl_Position = u_mvp * vec4(in_pos, 1.0); }}
-"""
-CUBE_FRAG = """#version 330 core
-uniform vec3 u_color;
-in vec3 v_normal;
-out vec4 fragColor;
-void main() {{
- vec3 n = normalize(v_normal);
- float diff = max(dot(n, normalize(vec3(0.4, 0.8, 0.5))), 0.0);
- fragColor = vec4(u_color * (0.25 + 0.75 * diff), 1.0);
-}}
-"""
-
-
-def _cube() -> np.ndarray:
- """36 vertices: position (3) + normal (3), interleaved float32."""
- faces = [((0, 0, 1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)),
- ((0, 0, -1), (1, -1, -1), (-1, -1, -1), (-1, 1, -1), (1, 1, -1)),
- ((1, 0, 0), (1, -1, 1), (1, -1, -1), (1, 1, -1), (1, 1, 1)),
- ((-1, 0, 0), (-1, -1, -1), (-1, -1, 1), (-1, 1, 1), (-1, 1, -1)),
- ((0, 1, 0), (-1, 1, 1), (1, 1, 1), (1, 1, -1), (-1, 1, -1)),
- ((0, -1, 0), (-1, -1, -1), (1, -1, -1), (1, -1, 1), (-1, -1, 1))]
- out = []
- for n, a, b, c, d in faces:
- for v in (a, b, c, a, c, d):
- out.extend(v)
- out.extend(n)
- return np.array(out, dtype="f4") * np.tile([0.5, 0.5, 0.5, 1, 1, 1], 36).astype("f4")
-
-
-def _perspective(fov_deg: float, aspect: float, near: float, far: float) -> np.ndarray:
- f = 1.0 / math.tan(math.radians(fov_deg) / 2.0)
- m = np.zeros((4, 4), dtype="f4")
- m[0, 0], m[1, 1] = f / aspect, f
- m[2, 2], m[2, 3] = (far + near) / (near - far), (2 * far * near) / (near - far)
- m[3, 2] = -1.0
- return m
-
-
-def _look_at(eye, target, up=(0, 1, 0)) -> np.ndarray:
- eye, target, up = np.array(eye, dtype="f4"), np.array(target, dtype="f4"), np.array(up, dtype="f4")
- f = target - eye
- f /= np.linalg.norm(f)
- s = np.cross(f, up)
- s /= np.linalg.norm(s)
- u = np.cross(s, f)
- m = np.identity(4, dtype="f4")
- m[0, :3], m[1, :3], m[2, :3] = s, u, -f
- m[:3, 3] = -m[:3, :3] @ eye
- return m
-
-
-def _rot_y(a: float) -> np.ndarray:
- c, s = math.cos(a), math.sin(a)
- return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype="f4")
-
-
-def setup(ctx: moderngl.Context, width: int, height: int):
- bg_prog = ctx.program(vertex_shader=BACKGROUND_VERT, fragment_shader=BACKGROUND_FRAG)
- quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
- bg_vao = ctx.vertex_array(bg_prog, [(quad, "2f", "in_pos")])
- cube_prog = ctx.program(vertex_shader=CUBE_VERT, fragment_shader=CUBE_FRAG)
- vbo = ctx.buffer(_cube().tobytes())
- cube_vao = ctx.vertex_array(cube_prog, [(vbo, "3f 3f", "in_pos", "in_normal")])
- proj = _perspective(45.0, width / height, 0.1, 100.0)
- view = _look_at((0.0, 1.2, 3.0), (0.0, 0.0, 0.0))
- # TODO build the plan's passes here (instancing, extra FBOs for post-processing, textures)
- return {{"bg_prog": bg_prog, "bg_vao": bg_vao, "cube_prog": cube_prog, "cube_vao": cube_vao, "proj": proj, "view": view}}
-
-
-def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
- fbo.use()
- ctx.disable(moderngl.DEPTH_TEST)
- state["bg_prog"]["u_time"].value = t
- state["bg_vao"].render(mode=moderngl.TRIANGLE_STRIP)
- ctx.enable(moderngl.DEPTH_TEST)
- model = _rot_y(t * 0.8)
- mvp = state["proj"] @ state["view"] @ model
- state["cube_prog"]["u_mvp"].write(mvp.T.astype("f4").tobytes()) # column-major for GLSL
- state["cube_prog"]["u_model"].write(model.T.astype("f4").tobytes())
- state["cube_prog"]["u_color"].value = (0.9, 0.6, 0.2)
- state["cube_vao"].render(mode=moderngl.TRIANGLES)
- # TODO replace the placeholder cube with the plan's content; keep drawing into `fbo` last
-'''
-
-
-def _comment_lines(prefix: str, items: list[str]) -> str:
- if not items:
- return f"{prefix}: (none)"
- return "\n".join(f" TODO {prefix} {i + 1}: {x}" for i, x in enumerate(items))
-
-
-def program_source(plan: GraphicsPlan | None) -> str:
- title = plan.title if plan else "untitled program"
- passes = [f"{p.name} ({p.kind}): {p.description}" for p in plan.passes] if plan else []
- visuals = list(plan.key_visuals) if plan else []
- return _TEMPLATE.format(
- title=title, summary=plan.summary if plan else "", style=plan.style if plan else "",
- motion=plan.motion if plan else "animate with t", duration=plan.duration_s if plan else 8.0,
- passes=_comment_lines("pass", passes), visuals=_comment_lines("key visual", visuals),
- )
-
-
-def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
- gplan = plan if isinstance(plan, GraphicsPlan) else None
- ws.src.mkdir(parents=True, exist_ok=True)
- p = ws.src / "program.py"
- p.write_text(program_source(gplan))
- return [p]
diff --git a/harness/codeverse/languages/scene_threejs/__init__.py b/harness/codeverse/languages/scene_threejs/__init__.py
index 377ea136..b51ac67a 100644
--- a/harness/codeverse/languages/scene_threejs/__init__.py
+++ b/harness/codeverse/languages/scene_threejs/__init__.py
@@ -1,5 +1,729 @@
"""scene_threejs: multi-file three.js scenes (+GLSL, +GLB assets) — lint, probe-build, skeleton, assembler."""
-from codeverse.languages.scene_threejs.runtime import SceneThreeJsRuntime
+from __future__ import annotations
-__all__ = ["SceneThreeJsRuntime"]
+import json
+import re
+import time
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan, ZonePlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.languages._js_lint import ImportKind, ImportVerdict, check_imports, node_check_syntax
+from codeverse.workspace import Workspace
+
+# ===================================================================== lint
+# (merged from codeverse/languages/scene_threejs/lint.py, 2026-08-28)
+GATE = "lint:scene_threejs"
+MAX_LINES = 800
+
+_CREATE_SCENE_RE = re.compile(r"export\s+(?:async\s+)?function\s+createScene\b|export\s+(?:const|let)\s+createScene\b|export\s*\{[^}]*\bcreateScene\b[^}]*\}")
+_BUILD_RE = re.compile(r"export\s+(?:async\s+)?function\s+build\b|export\s+(?:const|let)\s+build\b|export\s*\{[^}]*\bbuild\b[^}]*\}")
+_BUILD_ANY_RE = re.compile(r"export\s+(?:async\s+)?function\s+build[A-Za-z0-9_]*\b|export\s+(?:const|let)\s+build[A-Za-z0-9_]*\b")
+
+#: (regex, severity, message, hint)
+_PATTERNS: list[tuple[re.Pattern[str], Severity, str, str]] = [
+ (re.compile(r"\brequestAnimationFrame\s*\("), Severity.ERROR, "requestAnimationFrame: the host drives update(t, dt)", "delete your render loop; animate inside update(t, dt)"),
+ (re.compile(r"\bsetAnimationLoop\s*\("), Severity.ERROR, "renderer.setAnimationLoop: the host drives rendering", "remove it; animate inside update(t, dt)"),
+ (re.compile(r"new\s+THREE\.WebGLRenderer\b|new\s+WebGLRenderer\b|new\s+THREE\.WebGPURenderer\b"), Severity.ERROR, "creating a renderer: the host owns the WebGLRenderer", "use the `renderer` passed to createScene only for capability checks"),
+ (re.compile(r"\brenderer\.render\s*\("), Severity.ERROR, "renderer.render(): the host renders", "remove; return {scene, cameras, update} and let the host render"),
+ (re.compile(r"\bfetch\s*\(\s*['\"]https?://|XMLHttpRequest|new\s+WebSocket\b|['\"]https?://[^'\"]+\.(?:js|mjs|glb|gltf|png|jpg|hdr)['\"]"), Severity.ERROR, "network / CDN access", "no network: import 'three' / 'three/addons/*' and load assets from '/assets/<name>.glb'"),
+ (re.compile(r"\bdocument\.(?:body|getElementById|querySelector|querySelectorAll|head)\b|\bwindow\.addEventListener\b|\.innerHTML\b|\blocalStorage\b"), Severity.ERROR, "DOM/page access outside the host contract", "the host owns the page; only document.createElement('canvas') for procedural textures is allowed"),
+ (re.compile(r"\bTHREE\.Geometry\b|\bFace3\b|\bexamples/js/"), Severity.ERROR, "removed three.js API (Geometry/Face3/examples/js)", "use BufferGeometry and 'three/addons/...' imports"),
+ (re.compile(r"\b(?:Box|Plane|Sphere|Cylinder|Cone|Torus|Circle|Ring|Shape|Extrude|Lathe|Tube|Icosahedron|Dodecahedron|Octahedron|Tetrahedron|Polyhedron|Edges|Wireframe)BufferGeometry\b"), Severity.ERROR, "*BufferGeometry aliases were removed (r144)", "drop the 'Buffer' infix: THREE.BoxGeometry"),
+ (re.compile(r"\.outputEncoding\b|\bsRGBEncoding\b|\bLinearEncoding\b|\.encoding\s*="), Severity.ERROR, "texture/renderer .encoding was removed (r152)", "use texture.colorSpace = THREE.SRGBColorSpace (colour maps only)"),
+ (re.compile(r"\bMath\.random\s*\("), Severity.WARN, "Math.random makes renders non-reproducible", "use a seeded PRNG (e.g. mulberry32) so rounds can be compared"),
+ (re.compile(r"\brequire\s*\(|\bprocess\.env\b|\bmodule\.exports\b"), Severity.ERROR, "CommonJS / node globals in browser ESM", "use ESM import/export only"),
+ (re.compile(r"\bTHREE\.ImageUtils\b|\bTHREE\.SceneUtils\b|\bMeshFaceMaterial\b|\bMultiMaterial\b"), Severity.ERROR, "removed three.js helper", "use TextureLoader / material arrays"),
+]
+
+
+def _f(sev: Severity, msg: str, *, target: str, hint: str = "", **data: object) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=dict(data))
+
+
+def _js_files(ws: Workspace) -> list[Path]:
+ if not ws.src.is_dir():
+ return []
+ return sorted(p for p in ws.src.rglob("*.js") if "node_modules" not in p.parts) + sorted(ws.src.rglob("*.mjs"))
+
+
+def _node_check(path: Path, rel: str) -> GateFinding | None:
+ p = node_check_syntax(path, get_settings().binaries.node or "node")
+ if p is None:
+ return None
+ return _f(Severity.ERROR, f"syntax: {p.message}", target=f"{rel}:{p.line}" if p.line else rel,
+ hint="fix the syntax error at the quoted line (node --check)", line=p.line, detail=p.stderr_tail)
+
+
+def _check_imports(rel: str, text: str, ws: Workspace, path: Path) -> list[GateFinding]:
+ def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
+ tgt = f"{rel}:{line}"
+ if v.kind is ImportKind.ESCAPES:
+ return _f(Severity.ERROR, f"import '{spec}' escapes src/", target=tgt, hint="keep all code under src/")
+ if v.kind is ImportKind.MISSING:
+ return _f(Severity.ERROR, f"import of missing file '{spec}'", target=tgt,
+ hint="create the file or fix the path (relative imports need the .js extension)")
+ if v.kind is ImportKind.ABSOLUTE:
+ return _f(Severity.ERROR, f"absolute import '{spec}'", target=tgt, hint="use relative imports ('./x.js')")
+ return _f(Severity.ERROR, f"import '{spec}' is not allowed (only 'three', 'three/addons/*', relative files)", target=tgt,
+ hint="no CDN / npm packages; write the helper yourself in src/")
+
+ return check_imports(text, path, ws.src, make_finding=make_finding)[0]
+
+
+def lint(ws: Workspace) -> GateReport:
+ """Run all static checks; passed iff no ERROR findings."""
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ files = _js_files(ws)
+ scene = ws.src / "scene.js"
+ if not scene.is_file():
+ findings.append(_f(Severity.ERROR, "src/scene.js is missing", target="src/scene.js",
+ hint="create src/scene.js exporting createScene({THREE, renderer, loaders})"))
+ big: list[str] = []
+ for path in files:
+ rel = path.relative_to(ws.root).as_posix()
+ text = path.read_text(errors="replace")
+ syntax = _node_check(path, rel)
+ if syntax:
+ findings.append(syntax)
+ continue
+ findings.extend(_check_imports(rel, text, ws, path))
+ for pat, sev, msg, hint in _PATTERNS:
+ m = pat.search(text)
+ if m:
+ line = text.count("\n", 0, m.start()) + 1
+ findings.append(_f(sev, msg, target=f"{rel}:{line}", hint=hint))
+ n_lines = text.count("\n") + 1
+ if n_lines > MAX_LINES:
+ big.append(f"{rel} ({n_lines} lines)")
+ if path == scene and not _CREATE_SCENE_RE.search(text):
+ findings.append(_f(Severity.ERROR, "src/scene.js does not export createScene", target=rel,
+ hint="export function createScene({ THREE, renderer, loaders }) { ... return { scene, cameras, update } }"))
+ if path.parent == ws.src / "zones" and not _BUILD_RE.search(text):
+ findings.append(_f(Severity.ERROR, "zone module does not export build(ctx)", target=rel,
+ hint="export function build(ctx) { const g = new THREE.Group(); g.name = 'ZoneName'; ...; return g; }"))
+ if path.parent == ws.src / "assets" and not _BUILD_ANY_RE.search(text):
+ findings.append(_f(Severity.WARN, "asset module exports no build<Pascal>(THREE) factory", target=rel,
+ hint="export function buildLamp(THREE) { ... return group; }"))
+ for b in big:
+ findings.append(_f(Severity.WARN, f"large file {b} > {MAX_LINES} lines", target=b.split(" ")[0],
+ hint="split into zones/assets/shaders modules"))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+# ===================================================================== skeleton
+# (merged from codeverse/languages/scene_threejs/skeleton.py, 2026-08-28)
+STARTER_DIR = Path(__file__).resolve().parent / "starter" / "src"
+#: pattern files copied verbatim in plan mode (shown as reusable examples)
+PATTERN_FILES = ("shaders/sky.js", "shaders/water.js", "assets/pine_tree.js", "assets/windmill.js")
+
+
+def _write(path: Path, text: str, written: list[Path]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ written.append(path)
+
+
+def write_example(ws: Workspace) -> list[Path]:
+ """Copy the full example scene into ws.src (overwrites).
+
+ Raises when the starter tree is not there: rglob over a missing directory yields
+ nothing, so this used to write ZERO files and report success — which is exactly what
+ a non-editable (wheel) install produced before the starter tree was added to
+ package-data, and it surfaced much later as an empty scene rather than a bad install.
+ """
+ if not STARTER_DIR.is_dir():
+ raise FileNotFoundError(
+ f"scene_threejs starter tree missing: {STARTER_DIR} — this install has no package data "
+ f"(a non-editable install needs [tool.setuptools.package-data] to ship languages/**/starter/**/*)")
+ written: list[Path] = []
+ for src in sorted(STARTER_DIR.rglob("*.js")):
+ rel = src.relative_to(STARTER_DIR)
+ _write(ws.src / rel, src.read_text(), written)
+ if not written:
+ raise FileNotFoundError(f"scene_threejs starter tree at {STARTER_DIR} contains no .js files")
+ return written
+
+
+def _env_for_plan(plan: ScenePlan) -> str:
+ text = (STARTER_DIR / "env.js").read_text()
+ ex = plan.bounds.extents
+ span = max(ex[0], ex[2], 40.0)
+ ground = int(max(120, span * 2.5))
+ fog_near, fog_far = int(span * 0.8), int(max(span * 3.0, 200))
+ text = re.sub(r"export const GROUND_SIZE = \d+;", f"export const GROUND_SIZE = {ground};", text)
+ text = re.sub(r"const FOG_NEAR = \d+, FOG_FAR = \d+;", f"const FOG_NEAR = {fog_near}, FOG_FAR = {fog_far};", text)
+ text = re.sub(r"const SKY_RADIUS = \d+;", f"const SKY_RADIUS = {int(max(600, ground * 3))};", text)
+ header = (
+ f"// ENV PLAN: {plan.environment.strip()}\n"
+ f"// setting: {plan.setting.strip()} mood: {plan.mood.strip()}\n"
+ f"// bounds: centre {tuple(round(c, 1) for c in plan.bounds.center)} extents {tuple(round(e, 1) for e in ex)} m\n"
+ "// Rewrite the ground/sky/fog/sun below to match the plan; keep buildEnv/heightAt exports.\n"
+ )
+ return header + text
+
+
+def _asset_stub(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)
+ return f'''// src/assets/{snake}.js — asset "{pascal}": {a.description.strip()}
+// approx size {w:g} x {h:g} x {d:g} m (w x h x d); expected instances: ~{a.instances_hint}
+// CONTRACT: export function build{pascal}(THREE) → THREE.Group, origin at the base (y = 0), +Y up, +Z front, meters.
+// Build it from several parts with distinct materials (see assets/pine_tree.js, assets/windmill.js);
+// for many instances also export {snake}Parts(THREE) → [{{ geometry, material, castShadow }}].
+import * as THREE from 'three';
+
+export function build{pascal}(T = THREE) {{
+ const g = new T.Group();
+ g.name = '{pascal}';
+ // PLACEHOLDER blockout at the planned size — REPLACE with real construction.
+ const box = new T.Mesh(new T.BoxGeometry({w:g}, {h:g}, {d:g}), new T.MeshStandardMaterial({{ color: 0x9a9a9a, roughness: 0.8 }}));
+ box.position.y = {h / 2:g};
+ box.castShadow = box.receiveShadow = true;
+ g.add(box);
+ return g;
+}}
+'''
+
+
+def _zone_stub(z: ZonePlan, assets: dict[str, AssetPlan]) -> str:
+ snake, pascal = to_snake(z.name), to_pascal(z.name)
+ c, e = z.bbox.center, z.bbox.extents
+ imports, places = [], []
+ for i, name in enumerate(z.contents):
+ a = assets.get(to_snake(name))
+ if a is None:
+ continue
+ asn, asp = to_snake(a.name), to_pascal(a.name)
+ ox = (-e[0] / 4 + (i % 3) * e[0] / 4) if len(z.contents) > 1 else 0.0
+ oz = (-e[2] / 4 + (i // 3) * e[2] / 4) if len(z.contents) > 3 else 0.0
+ x, zz = round(c[0] + ox, 2), round(c[2] + oz, 2)
+ if a.kind == "threejs":
+ imports.append(f"import {{ build{asp} }} from '../assets/{asn}.js';")
+ places.append(f" place(build{asp}(THREE), {x}, {zz});")
+ else:
+ places.append(
+ f" if (ctx.assets && ctx.assets.{asn}) place(ctx.assets.{asn}.clone(), {x}, {zz});"
+ f" // GLB built in Blender → public/assets/{asn}.glb (preloaded by scene.js)"
+ )
+ imp = "\n".join(imports)
+ body = "\n".join(places) if places else " // TODO: build this zone's content here (use ctx.heightAt to seat objects)."
+ return f'''// src/zones/{snake}.js — zone "{pascal}": {z.description.strip()}
+// PLAN bbox: centre ({c[0]:g}, {c[1]:g}, {c[2]:g}) extents ({e[0]:g} x {e[1]:g} x {e[2]:g}) m. Contents: {", ".join(z.contents) or "-"}
+// CONTRACT: export function build(ctx) → THREE.Group named '{pascal}'. ctx = {{ THREE, scene, renderer, loaders, env, heightAt, assets }}
+// • seat objects on the ground with ctx.heightAt(x, z); keep everything inside the plan bbox
+// • repeats → THREE.InstancedMesh (see the pattern in assets/pine_tree.js: <asset>Parts(THREE))
+// • animation → zone.userData.update = (t, dt) => {{ ... }} (scene.js fans update() out to every zone)
+import * as THREE from 'three';
+{imp}
+
+export function build(ctx) {{
+ const {{ heightAt }} = ctx;
+ const zone = new THREE.Group();
+ zone.name = '{pascal}';
+ const place = (obj, x, z, ry = 0) => {{ obj.position.set(x, heightAt(x, z), z); obj.rotation.y = ry; zone.add(obj); return obj; }};
+{body}
+ zone.userData.update = (t, dt) => {{ /* animate zone elements here */ }};
+ return zone;
+}}
+'''
+
+
+def _scene_for_plan(plan: ScenePlan) -> str:
+ zones = [(to_snake(z.name), to_pascal(z.name)) for z in plan.zones]
+ glbs = [to_snake(a.name) for a in plan.assets if a.kind == "blender_glb"]
+ zone_imports = "\n".join(f"import {{ build as build{p} }} from './zones/{s}.js';" for s, p in zones)
+ zone_calls = ", ".join(f"build{p}(ctx)" for _, p in zones)
+ cams = ",\n".join(
+ f" {{ name: '{to_snake(c.name)}', position: [{c.position[0]:g}, {c.position[1]:g}, {c.position[2]:g}], "
+ f"lookAt: [{c.look_at[0]:g}, {c.look_at[1]:g}, {c.look_at[2]:g}], fov: {c.fov:g} }}"
+ + (f" // {c.purpose}" if c.purpose else "")
+ for c in plan.cameras[:6]
+ )
+ glb_block = ""
+ if glbs:
+ files = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
+ glb_block = f'''
+ // Blender-built assets (public/assets/*.glb) are preloaded once; zones clone ctx.assets.<name>.
+ const assetFiles = {{ {files} }};
+ const assets = {{}};
+ for (const [key, url] of Object.entries(assetFiles)) {{
+ try {{ assets[key] = (await loaders.gltf.loadAsync(url)).scene; }}
+ catch (e) {{ console.warn(`[assets] missing ${{url}} (${{e && e.message}}) — build it with Blender into public/assets/`); }}
+ }}
+ ctx.assets = assets;
+'''
+ async_kw = "async " if glbs else ""
+ header = (STARTER_DIR / "scene.js").read_text().split("import * as THREE")[0]
+ return f'''{header}// PLAN: {plan.title} — {plan.summary.strip()}
+// setting: {plan.setting.strip()} animation: {"; ".join(plan.animation) or "-"}
+import * as THREE from 'three';
+import {{ buildEnv, heightAt, SUN_AZIMUTH_DEG }} from './env.js';
+{zone_imports}
+
+export {async_kw}function createScene({{ THREE: T = THREE, renderer, loaders }}) {{
+ const scene = new THREE.Scene();
+ const ctx = {{ THREE, scene, renderer, loaders, heightAt, sunAzimuthDeg: SUN_AZIMUTH_DEG, assets: {{}} }};
+ const env = buildEnv(ctx);
+ ctx.env = env;
+{glb_block}
+ const zones = [{zone_calls}];
+ for (const z of zones) scene.add(z);
+
+ const cameras = [
+{cams}
+ ];
+
+ function update(t, dt) {{
+ if (env.update) env.update(t, dt);
+ for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
+ }}
+ return {{ scene, cameras, update }};
+}}
+'''
+
+
+def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
+ """Write starter files into ``ws.src``; returns the written paths."""
+ if plan is None or not isinstance(plan, ScenePlan):
+ return write_example(ws)
+ written: list[Path] = []
+ for rel in PATTERN_FILES:
+ _write(ws.src / rel, (STARTER_DIR / rel).read_text(), written)
+ _write(ws.src / "env.js", _env_for_plan(plan), written)
+ assets = {to_snake(a.name): a for a in plan.assets}
+ for a in plan.assets:
+ if a.kind == "threejs":
+ _write(ws.src / "assets" / f"{to_snake(a.name)}.js", _asset_stub(a), written)
+ for z in plan.zones:
+ _write(ws.src / "zones" / f"{to_snake(z.name)}.js", _zone_stub(z, assets), written)
+ _write(ws.src / "scene.js", _scene_for_plan(plan), written)
+ (ws.public / "assets").mkdir(parents=True, exist_ok=True)
+ return written
+
+
+# ===================================================================== assemble
+# (merged from codeverse/languages/scene_threejs/assemble.py, 2026-08-28)
+PROBE_REL = "src/_c3v_assemble_probe.js"
+_PREFIX = "[3dcv-assemble]"
+_SUN_RE = re.compile(r"export\s+const\s+SUN_AZIMUTH_DEG\s*=\s*(-?\d+(?:\.\d+)?)")
+
+
+class ZoneProbe(BaseModel):
+ name: str
+ file: str
+ ok: bool
+ error: str = ""
+ bbox: dict[str, Any] | None = None
+ meshes: int = 0
+ triangles: int = 0
+
+
+class ZoneProbeReport(BaseModel):
+ """``probe_zone_modules`` outcome. Unpacks as ``probes, census, other = ...``
+ (historical 3-tuple); ``camera_specs`` carries the driver-fitted cameras
+ (``{azimuth, overview, zones:[{group, position, lookAt, fov}]}``)."""
+
+ probes: dict[str, ZoneProbe] = Field(default_factory=dict)
+ census: dict[str, Any] = Field(default_factory=dict)
+ other_errors: list[str] = Field(default_factory=list)
+ camera_specs: dict[str, Any] = Field(default_factory=dict)
+
+ def __iter__(self): # type: ignore[override]
+ yield self.probes
+ yield self.census
+ yield self.other_errors
+
+
+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)
+
+
+def zone_files(ws: Workspace) -> list[Path]:
+ d = ws.src / "zones"
+ return sorted(p for p in d.glob("*.js") if not p.name.startswith("_")) if d.is_dir() else []
+
+
+def glb_assets(ws: Workspace) -> list[str]:
+ d = ws.public / "assets"
+ return sorted(p.stem for p in d.glob("*.glb")) if d.is_dir() else []
+
+
+def sun_azimuth(ws: Workspace, default: float = 45.0) -> float:
+ env = ws.src / "env.js"
+ if env.is_file():
+ m = _SUN_RE.search(env.read_text(errors="replace"))
+ if m:
+ return float(m.group(1))
+ return default
+
+
+# --------------------------------------------------------------------------- probing
+def _probe_module(zones: list[Path], glbs: list[str]) -> str:
+ entries = ",\n".join(f" ['{to_snake(p.stem)}', './zones/{p.name}']" for p in zones)
+ glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
+ return f"""// generated by codeverse assembler — probes env + zone modules independently; deleted after use
+import * as THREE from 'three';
+const ZONES = [
+{entries}
+];
+export async function createScene({{ renderer, loaders }}) {{
+ const scene = new THREE.Scene();
+ const ctx = {{ THREE, scene, renderer, loaders, heightAt: () => 0, assets: {{}}, env: {{}} }};
+ const assetFiles = {{ {glb_lines} }};
+ for (const [k, url] of Object.entries(assetFiles)) {{
+ try {{ ctx.assets[k] = (await loaders.gltf.loadAsync(url)).scene; }}
+ catch (e) {{ console.error('{_PREFIX} asset ' + k + ' failed: ' + ((e && e.message) || e)); }}
+ }}
+ let env = null;
+ try {{
+ const m = await import('./env.js');
+ if (typeof m.heightAt === 'function') ctx.heightAt = m.heightAt;
+ if (typeof m.buildEnv === 'function') env = await m.buildEnv(ctx);
+ ctx.env = env || {{}};
+ }} catch (e) {{ console.error('{_PREFIX} env failed: ' + ((e && e.stack) || e)); }}
+ const wraps = [];
+ for (const [name, rel] of ZONES) {{
+ try {{
+ const m = await import(rel);
+ if (typeof m.build !== 'function') throw new Error('module has no export build(ctx)');
+ const g = await m.build(ctx);
+ if (!g || !g.isObject3D) throw new Error('build(ctx) did not return a THREE.Object3D');
+ const wrap = new THREE.Group();
+ wrap.name = '__zone__' + name;
+ wrap.add(g);
+ scene.add(wrap);
+ wraps.push(wrap);
+ }} catch (e) {{ console.error('{_PREFIX} zone ' + name + ' failed: ' + ((e && e.stack) || e)); }}
+ }}
+ return {{
+ scene,
+ cameras: [{{ name: 'probe', position: [30, 20, 30], lookAt: [0, 0, 0], fov: 50 }}],
+ update(t, dt) {{
+ try {{ if (env && env.update) env.update(t, dt); }} catch (e) {{ console.error('{_PREFIX} env update failed: ' + e); }}
+ for (const w of wraps) {{
+ const z = w.children[0];
+ try {{ if (z && z.userData.update) z.userData.update(t, dt); }} catch (e) {{ console.error('{_PREFIX} zone ' + w.name.slice(8) + ' update failed: ' + e); }}
+ }}
+ }},
+ }};
+}}
+"""
+
+
+def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0, sun_azimuth_deg: float | None = None) -> ZoneProbeReport:
+ """Probe env + every zone module independently in the browser host.
+
+ Returns a :class:`ZoneProbeReport` (unpacks as the historical 3-tuple of
+ zone probes by snake name, census, other console errors). When
+ ``sun_azimuth_deg`` is given the driver also fits overview + per-group
+ cameras from the measured bboxes (``camera_specs``).
+ """
+ from codeverse.spatial.render_scene import run_scene_script
+
+ zones = zone_files(ws)
+ probe_path = ws.root / PROBE_REL
+ probe_path.write_text(_probe_module(zones, glb_assets(ws)))
+ args = ["--ws", str(ws.root), "--scene", PROBE_REL, "--timeout-ms", str(int(timeout_s * 1000))]
+ if sun_azimuth_deg is not None:
+ args += ["--sun-azimuth", str(sun_azimuth_deg)]
+ try:
+ res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)
+ finally:
+ probe_path.unlink(missing_ok=True)
+ s = res.summary
+ boot = s.get("boot") or {}
+ errors: list[str] = list(s.get("console_errors", []))
+ if not boot.get("ok"):
+ errors.insert(0, f"probe scene did not boot [{boot.get('stage')}]: {boot.get('error', '')}")
+ failed: dict[str, str] = {}
+ other: list[str] = []
+ for e in errors:
+ m = re.match(rf"(?:console: )?{re.escape(_PREFIX)} zone (\S+) failed: (.*)", e, re.S)
+ if m:
+ failed[m.group(1)] = m.group(2).strip()[:600]
+ else:
+ other.append(e)
+ census = s.get("census") or {}
+ groups = {g["name"]: g for g in census.get("groups", [])}
+ probes: dict[str, ZoneProbe] = {}
+ for p in zones:
+ name = to_snake(p.stem)
+ g = groups.get(f"__zone__{name}")
+ if name in failed or g is None:
+ probes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=False,
+ error=failed.get(name, "zone not present after probe (build returned nothing visible?)"))
+ else:
+ probes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=True, bbox=g.get("bbox"),
+ meshes=g.get("meshes", 0), triangles=g.get("triangles", 0))
+ return ZoneProbeReport(probes=probes, census=census, other_errors=other, camera_specs=s.get("fitted_cameras") or {})
+
+
+# --------------------------------------------------------------------------- cameras
+_FALLBACK_CAMERA = CameraPlan(name="overview", position=(30.0, 18.0, 30.0), look_at=(0.0, 1.0, 0.0), fov=50.0,
+ purpose="fallback: no measurable zones")
+
+
+def _plan_from_spec(spec: dict[str, Any], *, name: str, purpose: str) -> CameraPlan:
+ return CameraPlan(name=name, position=tuple(spec["position"]), look_at=tuple(spec["lookAt"]),
+ fov=float(spec.get("fov", 50.0)), purpose=purpose)
+
+
+def cameras_from_specs(specs: dict[str, Any], probes: dict[str, ZoneProbe], *, max_cameras: int = 6) -> list[CameraPlan]:
+ """Convert driver-fitted camera specs (``probe_scene.mjs --sun-azimuth``;
+ math owned by ``runtime_js/lib/orbit.mjs``) into CameraPlans: overview
+ first, then per-zone cameras, largest footprints first. Falls back to a
+ fixed overview when nothing was measurable."""
+ healthy = [p for p in probes.values() if p.ok and p.bbox]
+ overview = (specs or {}).get("overview")
+ if not healthy or not overview:
+ return [_FALLBACK_CAMERA.model_copy()]
+ cams = [_plan_from_spec(overview, name="overview", purpose="overview fitted to measured content bounds, sun side")]
+ by_zone = {str(z.get("group", "")).removeprefix("__zone__"): z for z in (specs or {}).get("zones", [])}
+ by_area = sorted(healthy, key=lambda p: -(p.bbox["size"][0] * p.bbox["size"][2]))
+ for p in by_area[: max_cameras - 1]:
+ spec = by_zone.get(p.name)
+ if spec:
+ cams.append(_plan_from_spec(spec, name=f"{to_snake(p.name)}_view", purpose=f"zone {to_pascal(p.name)} from the sun side"))
+ return cams
+
+
+# --------------------------------------------------------------------------- scene.js
+def _cam_literal(c: CameraPlan) -> str:
+ p, la = c.position, c.look_at
+ return (f" {{ name: '{to_snake(c.name)}', position: [{p[0]:g}, {p[1]:g}, {p[2]:g}], "
+ f"lookAt: [{la[0]:g}, {la[1]:g}, {la[2]:g}], fov: {c.fov:g} }},")
+
+
+def render_scene_js(zones: list[str], cameras: list[CameraPlan], glbs: list[str], *, env_ok: bool = True) -> str:
+ """Deterministic src/scene.js source for the given healthy zone snake names."""
+ imports = "\n".join(f"import {{ build as build{to_pascal(z)} }} from './zones/{z}.js';" for z in zones)
+ calls = "\n".join(f" await addZone(build{to_pascal(z)}, '{to_pascal(z)}');" for z in zones)
+ env_import = "import { buildEnv, heightAt } from './env.js';" if env_ok else ""
+ # buildEnv/build may be async (lint + the assembler probe both accept it): await consistently
+ env_build = " const env = (await buildEnv(ctx)) || {};\n ctx.env = env;" if env_ok else " const env = {};"
+ height = "heightAt" if env_ok else "() => 0"
+ glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
+ cams = "\n".join(_cam_literal(c) for c in cameras)
+ return f"""// src/scene.js — ASSEMBLED BY THE HARNESS (codeverse assembler). Edit zones/env instead; re-assembly overwrites this file.
+import * as THREE from 'three';
+{env_import}
+{imports}
+
+export async function createScene({{ renderer, loaders }}) {{
+ const scene = new THREE.Scene();
+ const ctx = {{ THREE, scene, renderer, loaders, heightAt: {height}, assets: {{}} }};
+ const assetFiles = {{ {glb_lines} }};
+ for (const [key, url] of Object.entries(assetFiles)) {{
+ try {{ ctx.assets[key] = (await loaders.gltf.loadAsync(url)).scene; }}
+ catch (e) {{ console.error(`[assets] failed to load ${{url}}: ${{e && e.message}}`); }}
+ }}
+{env_build}
+
+ const zones = [];
+ const addZone = async (build, name) => {{
+ const g = await build(ctx);
+ if (!g || !g.isObject3D) throw new Error(`zone ${{name}}: build(ctx) must return a THREE.Group`);
+ if (!g.name) g.name = name;
+ scene.add(g);
+ zones.push(g);
+ }};
+{calls}
+
+ const cameras = [
+{cams}
+ ];
+
+ function update(t, dt) {{
+ if (env.update) env.update(t, dt);
+ for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
+ }}
+ return {{ scene, cameras, update }};
+}}
+"""
+
+
+def assemble(ws: Workspace, plan: ScenePlan | None = None, *, cameras: str = "derive", probe: bool = True,
+ timeout_s: float = 90.0) -> AssembleResult:
+ """Probe zones, derive cameras, write ``src/scene.js``. ``cameras='plan'`` keeps the plan's."""
+ warnings: list[str] = []
+ zones = zone_files(ws)
+ if not zones:
+ raise FileNotFoundError(f"no zone modules under {ws.src / 'zones'}")
+ env_ok = (ws.src / "env.js").is_file()
+ if not env_ok:
+ warnings.append("src/env.js missing: scene assembled without env (flat ground at y=0, no lights unless zones add them)")
+ probes: dict[str, ZoneProbe] = {}
+ census: dict[str, Any] = {}
+ camera_specs: dict[str, Any] = {}
+ if probe:
+ report = probe_zone_modules(ws, timeout_s=timeout_s, sun_azimuth_deg=sun_azimuth(ws))
+ probes, census, camera_specs = report.probes, report.census, report.camera_specs
+ for o in report.other_errors:
+ if _PREFIX in o and "env failed" in o:
+ env_ok = False
+ warnings.append(f"env.js failed in probe; assembled without it: {o[:300]}")
+ else:
+ warnings.append(o[:300])
+ else:
+ probes = {to_snake(p.stem): ZoneProbe(name=to_snake(p.stem), file=f"src/zones/{p.name}", ok=True) for p in zones}
+ healthy = [n for n, p in probes.items() if p.ok]
+ failed = {n: p.error for n, p in probes.items() if not p.ok}
+ if not healthy:
+ warnings.append("no zone module survived probing; scene.js assembled with zero zones")
+ if cameras == "plan" and plan is not None and plan.cameras:
+ cams = list(plan.cameras[:6])
+ else:
+ cams = cameras_from_specs(camera_specs, probes)
+ text = render_scene_js(healthy, cams, glb_assets(ws), env_ok=env_ok)
+ out = ws.src / "scene.js"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(text)
+ (ws.artifacts).mkdir(parents=True, exist_ok=True)
+ result = AssembleResult(scene_path=str(out), zones_included=healthy, zones_failed=failed, env_ok=env_ok,
+ cameras=cams, warnings=warnings, census=census)
+ (ws.artifacts / "assemble.json").write_text(json.dumps(result.model_dump(mode="json"), indent=1))
+ return result
+
+
+# ===================================================================== runtime
+# (merged from codeverse/languages/scene_threejs/runtime.py, 2026-08-28)
+_HERE = Path(__file__).resolve().parent
+_PROMPTS = _HERE.parent.parent / "prompts" / "scene_threejs"
+
+
+class SceneThreeJsRuntime:
+ language = Language.SCENE_THREEJS
+ entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.SCENE_THREEJS], "src/zones/*.js", "src/assets/*.js", "src/env.js", "src/shaders/*.js")
+
+ 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 module-level gates function (class ns is not in method scope)
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ """Probe + shader preflight (one browser boot); ok iff the module loads
+ and no shader errors. External contract unchanged: the same two
+ GateReports land under ``artifacts/gates/``."""
+ from codeverse.config import get_settings
+
+ t0 = time.time()
+ tmo = min(float(timeout_s or get_settings().limits.build_timeout_s), 120.0)
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ # a probe/driver crash must not leave the previous round's census or the root
+ # driver outputs (scene_probe.json / shader_preflight.json) looking current;
+ # census.json is only rewritten `if census:` below, so it MUST be wiped here
+ ws.stage_artifacts("census.json", "scene_probe.json", "shader_preflight.json", "build.json").invalidate()
+ probe, shaders, census = _probe_and_preflight(ws, timeout_s=tmo)
+ if census:
+ (ws.artifacts / "census.json").write_text(json.dumps(census, indent=1))
+ gates_dir = ws.artifacts / "gates"
+ gates_dir.mkdir(exist_ok=True)
+ (gates_dir / "scene_probe.json").write_text(probe.model_dump_json(indent=1))
+ (gates_dir / "shader_preflight.json").write_text(shaders.model_dump_json(indent=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,
+ language=self.language.value,
+ glb_path=None,
+ extra_paths={
+ "census": str(ws.artifacts / "census.json"),
+ "scene_probe": str(gates_dir / "scene_probe.json"),
+ "shader_preflight": str(gates_dir / "shader_preflight.json"),
+ },
+ 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,
+ duration_ms=int((time.time() - t0) * 1000),
+ census=census,
+ )
+ (ws.artifacts / "build.json").write_text(json.dumps(res.model_dump(mode="json"), indent=1))
+ return res
+
+ def contract_doc(self) -> str:
+ p = _PROMPTS / "contract.md"
+ if p.is_file():
+ return p.read_text()
+ return (_HERE / "CONTRACT.md").read_text()
+
+ def cookbook_path(self) -> Path:
+ return _PROMPTS / "cookbook.md"
+
+
+def _probe_and_preflight(ws: Workspace, *, timeout_s: float) -> tuple[GateReport, GateReport, dict]:
+ """One ``probe_scene.mjs --compile`` run → (scene_probe, shader_preflight, census).
+
+ The driver boots the scene once and runs both stages on the same page;
+ when the scene never boots the preflight is skipped, matching the old
+ two-call behaviour (a failed-empty shader gate).
+ """
+ from codeverse.contracts.artifacts import GateFinding
+ from codeverse.spatial.probes import PROBE_GATE, SHADER_GATE, probe_report, shader_report
+ from codeverse.spatial.render_scene import SceneRenderError, run_scene_script
+
+ t0 = time.time()
+ args = [
+ "--ws", str(ws.root), "--compile",
+ "--out", str(ws.artifacts / "scene_probe.json"),
+ "--shaders-out", str(ws.artifacts / "shader_preflight.json"),
+ "--timeout-ms", str(int(timeout_s * 1000)),
+ ]
+ try:
+ res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)
+ except SceneRenderError as e:
+ dur = int((time.time() - t0) * 1000)
+ finding = GateFinding(gate=PROBE_GATE, severity=Severity.ERROR, target="src/scene.js",
+ message=f"scene probe could not run: {e}"[:1500],
+ fix_hint="this is a harness/driver failure, not your code; retry or report",
+ data={"harness_failure": True})
+ return (GateReport(gate=PROBE_GATE, passed=False, findings=[finding], duration_ms=dur),
+ GateReport(gate=SHADER_GATE, passed=False, findings=[]), {})
+ dur = int((time.time() - t0) * 1000)
+ probe, census = probe_report(res.summary, duration_ms=dur)
+ rep = res.summary.get("shader_report") or {}
+ if not rep or rep.get("skipped"):
+ shaders = GateReport(gate=SHADER_GATE, passed=False, findings=[])
+ else:
+ shaders = shader_report(rep, duration_ms=int(rep.get("duration_ms") or 0))
+ return probe, shaders, census
+
+
+def _summary_text(probe: GateReport, shaders: GateReport) -> str:
+ lines = [f"scene_probe: {'ok' if probe.passed else 'FAILED'} ({len(probe.errors)} errors)"]
+ lines += [f" - {f.target or ''}: {f.message}"[:400] for f in probe.findings if f.severity != Severity.INFO][:12]
+ lines.append(f"shader_preflight: {'ok' if shaders.passed else 'FAILED'} ({len(shaders.errors)} errors)")
+ 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/codeverse/languages/scene_threejs/assemble.py b/harness/codeverse/languages/scene_threejs/assemble.py
deleted file mode 100644
index ddf34476..00000000
--- a/harness/codeverse/languages/scene_threejs/assemble.py
+++ /dev/null
@@ -1,317 +0,0 @@
-"""Deterministic scene assembler for the scene track's parallel mode.
-
-Zone agents write ``src/zones/<snake>.js`` (``build(ctx) → Group``) and an env
-agent writes ``src/env.js``; this module (code, not an LLM) then:
-
-1. probes every zone module in the browser host (``probe_zone_modules``),
- passing the sun azimuth (``SUN_AZIMUTH_DEG`` from env.js): does it import,
- does ``build(ctx)`` return an Object3D, what is its bbox — and the driver
- (``probe_scene.mjs --sun-azimuth``, camera math owned by
- ``runtime_js/lib/orbit.mjs``) fits overview + per-zone cameras, eye on the
- sun side, from the measured bboxes;
-2. converts those fitted specs into ``CameraPlan``s (``cameras_from_specs``;
- the only camera math left in python is the no-measurable-zones fallback);
-3. writes ``src/scene.js`` importing only the healthy zones, naming groups,
- preloading ``public/assets/*.glb`` into ``ctx.assets`` and fanning
- ``update(t, dt)`` out to env + zones (``assemble``).
-"""
-
-from __future__ import annotations
-
-import json
-import re
-from pathlib import Path
-from typing import Any
-
-from pydantic import BaseModel, Field
-
-from codeverse.contracts.plan import CameraPlan, ScenePlan
-from codeverse.conventions import to_pascal, to_snake
-from codeverse.workspace import Workspace
-
-PROBE_REL = "src/_c3v_assemble_probe.js"
-_PREFIX = "[3dcv-assemble]"
-_SUN_RE = re.compile(r"export\s+const\s+SUN_AZIMUTH_DEG\s*=\s*(-?\d+(?:\.\d+)?)")
-
-
-class ZoneProbe(BaseModel):
- name: str
- file: str
- ok: bool
- error: str = ""
- bbox: dict[str, Any] | None = None
- meshes: int = 0
- triangles: int = 0
-
-
-class ZoneProbeReport(BaseModel):
- """``probe_zone_modules`` outcome. Unpacks as ``probes, census, other = ...``
- (historical 3-tuple); ``camera_specs`` carries the driver-fitted cameras
- (``{azimuth, overview, zones:[{group, position, lookAt, fov}]}``)."""
-
- probes: dict[str, ZoneProbe] = Field(default_factory=dict)
- census: dict[str, Any] = Field(default_factory=dict)
- other_errors: list[str] = Field(default_factory=list)
- camera_specs: dict[str, Any] = Field(default_factory=dict)
-
- def __iter__(self): # type: ignore[override]
- yield self.probes
- yield self.census
- yield self.other_errors
-
-
-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)
-
-
-def zone_files(ws: Workspace) -> list[Path]:
- d = ws.src / "zones"
- return sorted(p for p in d.glob("*.js") if not p.name.startswith("_")) if d.is_dir() else []
-
-
-def glb_assets(ws: Workspace) -> list[str]:
- d = ws.public / "assets"
- return sorted(p.stem for p in d.glob("*.glb")) if d.is_dir() else []
-
-
-def sun_azimuth(ws: Workspace, default: float = 45.0) -> float:
- env = ws.src / "env.js"
- if env.is_file():
- m = _SUN_RE.search(env.read_text(errors="replace"))
- if m:
- return float(m.group(1))
- return default
-
-
-# --------------------------------------------------------------------------- probing
-def _probe_module(zones: list[Path], glbs: list[str]) -> str:
- entries = ",\n".join(f" ['{to_snake(p.stem)}', './zones/{p.name}']" for p in zones)
- glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
- return f"""// generated by codeverse assembler — probes env + zone modules independently; deleted after use
-import * as THREE from 'three';
-const ZONES = [
-{entries}
-];
-export async function createScene({{ renderer, loaders }}) {{
- const scene = new THREE.Scene();
- const ctx = {{ THREE, scene, renderer, loaders, heightAt: () => 0, assets: {{}}, env: {{}} }};
- const assetFiles = {{ {glb_lines} }};
- for (const [k, url] of Object.entries(assetFiles)) {{
- try {{ ctx.assets[k] = (await loaders.gltf.loadAsync(url)).scene; }}
- catch (e) {{ console.error('{_PREFIX} asset ' + k + ' failed: ' + ((e && e.message) || e)); }}
- }}
- let env = null;
- try {{
- const m = await import('./env.js');
- if (typeof m.heightAt === 'function') ctx.heightAt = m.heightAt;
- if (typeof m.buildEnv === 'function') env = await m.buildEnv(ctx);
- ctx.env = env || {{}};
- }} catch (e) {{ console.error('{_PREFIX} env failed: ' + ((e && e.stack) || e)); }}
- const wraps = [];
- for (const [name, rel] of ZONES) {{
- try {{
- const m = await import(rel);
- if (typeof m.build !== 'function') throw new Error('module has no export build(ctx)');
- const g = await m.build(ctx);
- if (!g || !g.isObject3D) throw new Error('build(ctx) did not return a THREE.Object3D');
- const wrap = new THREE.Group();
- wrap.name = '__zone__' + name;
- wrap.add(g);
- scene.add(wrap);
- wraps.push(wrap);
- }} catch (e) {{ console.error('{_PREFIX} zone ' + name + ' failed: ' + ((e && e.stack) || e)); }}
- }}
- return {{
- scene,
- cameras: [{{ name: 'probe', position: [30, 20, 30], lookAt: [0, 0, 0], fov: 50 }}],
- update(t, dt) {{
- try {{ if (env && env.update) env.update(t, dt); }} catch (e) {{ console.error('{_PREFIX} env update failed: ' + e); }}
- for (const w of wraps) {{
- const z = w.children[0];
- try {{ if (z && z.userData.update) z.userData.update(t, dt); }} catch (e) {{ console.error('{_PREFIX} zone ' + w.name.slice(8) + ' update failed: ' + e); }}
- }}
- }},
- }};
-}}
-"""
-
-
-def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0, sun_azimuth_deg: float | None = None) -> ZoneProbeReport:
- """Probe env + every zone module independently in the browser host.
-
- Returns a :class:`ZoneProbeReport` (unpacks as the historical 3-tuple of
- zone probes by snake name, census, other console errors). When
- ``sun_azimuth_deg`` is given the driver also fits overview + per-group
- cameras from the measured bboxes (``camera_specs``).
- """
- from codeverse.spatial.render_scene import run_scene_script
-
- zones = zone_files(ws)
- probe_path = ws.root / PROBE_REL
- probe_path.write_text(_probe_module(zones, glb_assets(ws)))
- args = ["--ws", str(ws.root), "--scene", PROBE_REL, "--timeout-ms", str(int(timeout_s * 1000))]
- if sun_azimuth_deg is not None:
- args += ["--sun-azimuth", str(sun_azimuth_deg)]
- try:
- res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)
- finally:
- probe_path.unlink(missing_ok=True)
- s = res.summary
- boot = s.get("boot") or {}
- errors: list[str] = list(s.get("console_errors", []))
- if not boot.get("ok"):
- errors.insert(0, f"probe scene did not boot [{boot.get('stage')}]: {boot.get('error', '')}")
- failed: dict[str, str] = {}
- other: list[str] = []
- for e in errors:
- m = re.match(rf"(?:console: )?{re.escape(_PREFIX)} zone (\S+) failed: (.*)", e, re.S)
- if m:
- failed[m.group(1)] = m.group(2).strip()[:600]
- else:
- other.append(e)
- census = s.get("census") or {}
- groups = {g["name"]: g for g in census.get("groups", [])}
- probes: dict[str, ZoneProbe] = {}
- for p in zones:
- name = to_snake(p.stem)
- g = groups.get(f"__zone__{name}")
- if name in failed or g is None:
- probes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=False,
- error=failed.get(name, "zone not present after probe (build returned nothing visible?)"))
- else:
- probes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=True, bbox=g.get("bbox"),
- meshes=g.get("meshes", 0), triangles=g.get("triangles", 0))
- return ZoneProbeReport(probes=probes, census=census, other_errors=other, camera_specs=s.get("fitted_cameras") or {})
-
-
-# --------------------------------------------------------------------------- cameras
-_FALLBACK_CAMERA = CameraPlan(name="overview", position=(30.0, 18.0, 30.0), look_at=(0.0, 1.0, 0.0), fov=50.0,
- purpose="fallback: no measurable zones")
-
-
-def _plan_from_spec(spec: dict[str, Any], *, name: str, purpose: str) -> CameraPlan:
- return CameraPlan(name=name, position=tuple(spec["position"]), look_at=tuple(spec["lookAt"]),
- fov=float(spec.get("fov", 50.0)), purpose=purpose)
-
-
-def cameras_from_specs(specs: dict[str, Any], probes: dict[str, ZoneProbe], *, max_cameras: int = 6) -> list[CameraPlan]:
- """Convert driver-fitted camera specs (``probe_scene.mjs --sun-azimuth``;
- math owned by ``runtime_js/lib/orbit.mjs``) into CameraPlans: overview
- first, then per-zone cameras, largest footprints first. Falls back to a
- fixed overview when nothing was measurable."""
- healthy = [p for p in probes.values() if p.ok and p.bbox]
- overview = (specs or {}).get("overview")
- if not healthy or not overview:
- return [_FALLBACK_CAMERA.model_copy()]
- cams = [_plan_from_spec(overview, name="overview", purpose="overview fitted to measured content bounds, sun side")]
- by_zone = {str(z.get("group", "")).removeprefix("__zone__"): z for z in (specs or {}).get("zones", [])}
- by_area = sorted(healthy, key=lambda p: -(p.bbox["size"][0] * p.bbox["size"][2]))
- for p in by_area[: max_cameras - 1]:
- spec = by_zone.get(p.name)
- if spec:
- cams.append(_plan_from_spec(spec, name=f"{to_snake(p.name)}_view", purpose=f"zone {to_pascal(p.name)} from the sun side"))
- return cams
-
-
-# --------------------------------------------------------------------------- scene.js
-def _cam_literal(c: CameraPlan) -> str:
- p, la = c.position, c.look_at
- return (f" {{ name: '{to_snake(c.name)}', position: [{p[0]:g}, {p[1]:g}, {p[2]:g}], "
- f"lookAt: [{la[0]:g}, {la[1]:g}, {la[2]:g}], fov: {c.fov:g} }},")
-
-
-def render_scene_js(zones: list[str], cameras: list[CameraPlan], glbs: list[str], *, env_ok: bool = True) -> str:
- """Deterministic src/scene.js source for the given healthy zone snake names."""
- imports = "\n".join(f"import {{ build as build{to_pascal(z)} }} from './zones/{z}.js';" for z in zones)
- calls = "\n".join(f" await addZone(build{to_pascal(z)}, '{to_pascal(z)}');" for z in zones)
- env_import = "import { buildEnv, heightAt } from './env.js';" if env_ok else ""
- # buildEnv/build may be async (lint + the assembler probe both accept it): await consistently
- env_build = " const env = (await buildEnv(ctx)) || {};\n ctx.env = env;" if env_ok else " const env = {};"
- height = "heightAt" if env_ok else "() => 0"
- glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
- cams = "\n".join(_cam_literal(c) for c in cameras)
- return f"""// src/scene.js — ASSEMBLED BY THE HARNESS (codeverse assembler). Edit zones/env instead; re-assembly overwrites this file.
-import * as THREE from 'three';
-{env_import}
-{imports}
-
-export async function createScene({{ renderer, loaders }}) {{
- const scene = new THREE.Scene();
- const ctx = {{ THREE, scene, renderer, loaders, heightAt: {height}, assets: {{}} }};
- const assetFiles = {{ {glb_lines} }};
- for (const [key, url] of Object.entries(assetFiles)) {{
- try {{ ctx.assets[key] = (await loaders.gltf.loadAsync(url)).scene; }}
- catch (e) {{ console.error(`[assets] failed to load ${{url}}: ${{e && e.message}}`); }}
- }}
-{env_build}
-
- const zones = [];
- const addZone = async (build, name) => {{
- const g = await build(ctx);
- if (!g || !g.isObject3D) throw new Error(`zone ${{name}}: build(ctx) must return a THREE.Group`);
- if (!g.name) g.name = name;
- scene.add(g);
- zones.push(g);
- }};
-{calls}
-
- const cameras = [
-{cams}
- ];
-
- function update(t, dt) {{
- if (env.update) env.update(t, dt);
- for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
- }}
- return {{ scene, cameras, update }};
-}}
-"""
-
-
-def assemble(ws: Workspace, plan: ScenePlan | None = None, *, cameras: str = "derive", probe: bool = True,
- timeout_s: float = 90.0) -> AssembleResult:
- """Probe zones, derive cameras, write ``src/scene.js``. ``cameras='plan'`` keeps the plan's."""
- warnings: list[str] = []
- zones = zone_files(ws)
- if not zones:
- raise FileNotFoundError(f"no zone modules under {ws.src / 'zones'}")
- env_ok = (ws.src / "env.js").is_file()
- if not env_ok:
- warnings.append("src/env.js missing: scene assembled without env (flat ground at y=0, no lights unless zones add them)")
- probes: dict[str, ZoneProbe] = {}
- census: dict[str, Any] = {}
- camera_specs: dict[str, Any] = {}
- if probe:
- report = probe_zone_modules(ws, timeout_s=timeout_s, sun_azimuth_deg=sun_azimuth(ws))
- probes, census, camera_specs = report.probes, report.census, report.camera_specs
- for o in report.other_errors:
- if _PREFIX in o and "env failed" in o:
- env_ok = False
- warnings.append(f"env.js failed in probe; assembled without it: {o[:300]}")
- else:
- warnings.append(o[:300])
- else:
- probes = {to_snake(p.stem): ZoneProbe(name=to_snake(p.stem), file=f"src/zones/{p.name}", ok=True) for p in zones}
- healthy = [n for n, p in probes.items() if p.ok]
- failed = {n: p.error for n, p in probes.items() if not p.ok}
- if not healthy:
- warnings.append("no zone module survived probing; scene.js assembled with zero zones")
- if cameras == "plan" and plan is not None and plan.cameras:
- cams = list(plan.cameras[:6])
- else:
- cams = cameras_from_specs(camera_specs, probes)
- text = render_scene_js(healthy, cams, glb_assets(ws), env_ok=env_ok)
- out = ws.src / "scene.js"
- out.parent.mkdir(parents=True, exist_ok=True)
- out.write_text(text)
- (ws.artifacts).mkdir(parents=True, exist_ok=True)
- result = AssembleResult(scene_path=str(out), zones_included=healthy, zones_failed=failed, env_ok=env_ok,
- cameras=cams, warnings=warnings, census=census)
- (ws.artifacts / "assemble.json").write_text(json.dumps(result.model_dump(mode="json"), indent=1))
- return result
diff --git a/harness/codeverse/languages/scene_threejs/lint.py b/harness/codeverse/languages/scene_threejs/lint.py
deleted file mode 100644
index a4af0193..00000000
--- a/harness/codeverse/languages/scene_threejs/lint.py
+++ /dev/null
@@ -1,118 +0,0 @@
-"""Static lint for ``scene_threejs`` workspaces (no browser).
-
-Checks: ``node --check`` syntax per file, import allowlist ('three',
-'three/addons/*', relative — side-effect ``import './x.js'`` is matched too, so a
-bare import of a missing file is flagged), forbidden network/DOM/render-loop
-usage, required exports (``createScene`` in src/scene.js, ``build`` in zones),
-removed three.js APIs, oversized files. Returns a GateReport ``lint:scene_threejs``.
-"""
-
-from __future__ import annotations
-
-import re
-import time
-from pathlib import Path
-
-from codeverse.config import get_settings
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.languages._js_lint import ImportKind, ImportVerdict, check_imports, node_check_syntax
-from codeverse.workspace import Workspace
-
-GATE = "lint:scene_threejs"
-MAX_LINES = 800
-
-_CREATE_SCENE_RE = re.compile(r"export\s+(?:async\s+)?function\s+createScene\b|export\s+(?:const|let)\s+createScene\b|export\s*\{[^}]*\bcreateScene\b[^}]*\}")
-_BUILD_RE = re.compile(r"export\s+(?:async\s+)?function\s+build\b|export\s+(?:const|let)\s+build\b|export\s*\{[^}]*\bbuild\b[^}]*\}")
-_BUILD_ANY_RE = re.compile(r"export\s+(?:async\s+)?function\s+build[A-Za-z0-9_]*\b|export\s+(?:const|let)\s+build[A-Za-z0-9_]*\b")
-
-#: (regex, severity, message, hint)
-_PATTERNS: list[tuple[re.Pattern[str], Severity, str, str]] = [
- (re.compile(r"\brequestAnimationFrame\s*\("), Severity.ERROR, "requestAnimationFrame: the host drives update(t, dt)", "delete your render loop; animate inside update(t, dt)"),
- (re.compile(r"\bsetAnimationLoop\s*\("), Severity.ERROR, "renderer.setAnimationLoop: the host drives rendering", "remove it; animate inside update(t, dt)"),
- (re.compile(r"new\s+THREE\.WebGLRenderer\b|new\s+WebGLRenderer\b|new\s+THREE\.WebGPURenderer\b"), Severity.ERROR, "creating a renderer: the host owns the WebGLRenderer", "use the `renderer` passed to createScene only for capability checks"),
- (re.compile(r"\brenderer\.render\s*\("), Severity.ERROR, "renderer.render(): the host renders", "remove; return {scene, cameras, update} and let the host render"),
- (re.compile(r"\bfetch\s*\(\s*['\"]https?://|XMLHttpRequest|new\s+WebSocket\b|['\"]https?://[^'\"]+\.(?:js|mjs|glb|gltf|png|jpg|hdr)['\"]"), Severity.ERROR, "network / CDN access", "no network: import 'three' / 'three/addons/*' and load assets from '/assets/<name>.glb'"),
- (re.compile(r"\bdocument\.(?:body|getElementById|querySelector|querySelectorAll|head)\b|\bwindow\.addEventListener\b|\.innerHTML\b|\blocalStorage\b"), Severity.ERROR, "DOM/page access outside the host contract", "the host owns the page; only document.createElement('canvas') for procedural textures is allowed"),
- (re.compile(r"\bTHREE\.Geometry\b|\bFace3\b|\bexamples/js/"), Severity.ERROR, "removed three.js API (Geometry/Face3/examples/js)", "use BufferGeometry and 'three/addons/...' imports"),
- (re.compile(r"\b(?:Box|Plane|Sphere|Cylinder|Cone|Torus|Circle|Ring|Shape|Extrude|Lathe|Tube|Icosahedron|Dodecahedron|Octahedron|Tetrahedron|Polyhedron|Edges|Wireframe)BufferGeometry\b"), Severity.ERROR, "*BufferGeometry aliases were removed (r144)", "drop the 'Buffer' infix: THREE.BoxGeometry"),
- (re.compile(r"\.outputEncoding\b|\bsRGBEncoding\b|\bLinearEncoding\b|\.encoding\s*="), Severity.ERROR, "texture/renderer .encoding was removed (r152)", "use texture.colorSpace = THREE.SRGBColorSpace (colour maps only)"),
- (re.compile(r"\bMath\.random\s*\("), Severity.WARN, "Math.random makes renders non-reproducible", "use a seeded PRNG (e.g. mulberry32) so rounds can be compared"),
- (re.compile(r"\brequire\s*\(|\bprocess\.env\b|\bmodule\.exports\b"), Severity.ERROR, "CommonJS / node globals in browser ESM", "use ESM import/export only"),
- (re.compile(r"\bTHREE\.ImageUtils\b|\bTHREE\.SceneUtils\b|\bMeshFaceMaterial\b|\bMultiMaterial\b"), Severity.ERROR, "removed three.js helper", "use TextureLoader / material arrays"),
-]
-
-
-def _f(sev: Severity, msg: str, *, target: str, hint: str = "", **data: object) -> GateFinding:
- return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=dict(data))
-
-
-def _js_files(ws: Workspace) -> list[Path]:
- if not ws.src.is_dir():
- return []
- return sorted(p for p in ws.src.rglob("*.js") if "node_modules" not in p.parts) + sorted(ws.src.rglob("*.mjs"))
-
-
-def _node_check(path: Path, rel: str) -> GateFinding | None:
- p = node_check_syntax(path, get_settings().binaries.node or "node")
- if p is None:
- return None
- return _f(Severity.ERROR, f"syntax: {p.message}", target=f"{rel}:{p.line}" if p.line else rel,
- hint="fix the syntax error at the quoted line (node --check)", line=p.line, detail=p.stderr_tail)
-
-
-def _check_imports(rel: str, text: str, ws: Workspace, path: Path) -> list[GateFinding]:
- def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
- tgt = f"{rel}:{line}"
- if v.kind is ImportKind.ESCAPES:
- return _f(Severity.ERROR, f"import '{spec}' escapes src/", target=tgt, hint="keep all code under src/")
- if v.kind is ImportKind.MISSING:
- return _f(Severity.ERROR, f"import of missing file '{spec}'", target=tgt,
- hint="create the file or fix the path (relative imports need the .js extension)")
- if v.kind is ImportKind.ABSOLUTE:
- return _f(Severity.ERROR, f"absolute import '{spec}'", target=tgt, hint="use relative imports ('./x.js')")
- return _f(Severity.ERROR, f"import '{spec}' is not allowed (only 'three', 'three/addons/*', relative files)", target=tgt,
- hint="no CDN / npm packages; write the helper yourself in src/")
-
- return check_imports(text, path, ws.src, make_finding=make_finding)[0]
-
-
-def lint(ws: Workspace) -> GateReport:
- """Run all static checks; passed iff no ERROR findings."""
- t0 = time.time()
- findings: list[GateFinding] = []
- files = _js_files(ws)
- scene = ws.src / "scene.js"
- if not scene.is_file():
- findings.append(_f(Severity.ERROR, "src/scene.js is missing", target="src/scene.js",
- hint="create src/scene.js exporting createScene({THREE, renderer, loaders})"))
- big: list[str] = []
- for path in files:
- rel = path.relative_to(ws.root).as_posix()
- text = path.read_text(errors="replace")
- syntax = _node_check(path, rel)
- if syntax:
- findings.append(syntax)
- continue
- findings.extend(_check_imports(rel, text, ws, path))
- for pat, sev, msg, hint in _PATTERNS:
- m = pat.search(text)
- if m:
- line = text.count("\n", 0, m.start()) + 1
- findings.append(_f(sev, msg, target=f"{rel}:{line}", hint=hint))
- n_lines = text.count("\n") + 1
- if n_lines > MAX_LINES:
- big.append(f"{rel} ({n_lines} lines)")
- if path == scene and not _CREATE_SCENE_RE.search(text):
- findings.append(_f(Severity.ERROR, "src/scene.js does not export createScene", target=rel,
- hint="export function createScene({ THREE, renderer, loaders }) { ... return { scene, cameras, update } }"))
- if path.parent == ws.src / "zones" and not _BUILD_RE.search(text):
- findings.append(_f(Severity.ERROR, "zone module does not export build(ctx)", target=rel,
- hint="export function build(ctx) { const g = new THREE.Group(); g.name = 'ZoneName'; ...; return g; }"))
- if path.parent == ws.src / "assets" and not _BUILD_ANY_RE.search(text):
- findings.append(_f(Severity.WARN, "asset module exports no build<Pascal>(THREE) factory", target=rel,
- hint="export function buildLamp(THREE) { ... return group; }"))
- for b in big:
- findings.append(_f(Severity.WARN, f"large file {b} > {MAX_LINES} lines", target=b.split(" ")[0],
- hint="split into zones/assets/shaders modules"))
- passed = not any(f.severity == Severity.ERROR for f in findings)
- return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/languages/scene_threejs/runtime.py b/harness/codeverse/languages/scene_threejs/runtime.py
deleted file mode 100644
index b063e40d..00000000
--- a/harness/codeverse/languages/scene_threejs/runtime.py
+++ /dev/null
@@ -1,146 +0,0 @@
-"""``SceneThreeJsRuntime``: the LanguageRuntime for multi-file three.js scenes.
-
-build(ws) = ONE ``probe_scene.mjs --compile`` run (single browser boot) that
-yields both gates: ``scene_probe`` (module loads, shape, cameras, update,
-census) and ``shader_preflight`` (static GLSL audits + GPU compile preflight).
-A scene has no GLB deliverable — ``BuildResult.glb_path`` stays None; the
-census, probe and preflight JSONs are in ``extra_paths``.
-"""
-
-from __future__ import annotations
-
-import json
-import time
-from pathlib import Path
-
-from codeverse.contracts.artifacts import BuildResult, GateReport, Severity
-from codeverse.contracts.common import ENTRY_FILE, Language
-from codeverse.contracts.plan import Plan
-from codeverse.languages.scene_threejs.lint import lint as _lint
-from codeverse.languages.scene_threejs.skeleton import write_skeleton
-from codeverse.workspace import Workspace
-
-_HERE = Path(__file__).resolve().parent
-_PROMPTS = _HERE.parent.parent / "prompts" / "scene_threejs"
-
-
-class SceneThreeJsRuntime:
- language = Language.SCENE_THREEJS
- entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.SCENE_THREEJS], "src/zones/*.js", "src/assets/*.js", "src/env.js", "src/shaders/*.js")
-
- def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
- return write_skeleton(ws, plan)
-
- def lint(self, ws: Workspace) -> GateReport:
- return _lint(ws)
-
- def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
- """Probe + shader preflight (one browser boot); ok iff the module loads
- and no shader errors. External contract unchanged: the same two
- GateReports land under ``artifacts/gates/``."""
- from codeverse.config import get_settings
-
- t0 = time.time()
- tmo = min(float(timeout_s or get_settings().limits.build_timeout_s), 120.0)
- ws.artifacts.mkdir(parents=True, exist_ok=True)
- # a probe/driver crash must not leave the previous round's census or the root
- # driver outputs (scene_probe.json / shader_preflight.json) looking current;
- # census.json is only rewritten `if census:` below, so it MUST be wiped here
- ws.stage_artifacts("census.json", "scene_probe.json", "shader_preflight.json", "build.json").invalidate()
- probe, shaders, census = _probe_and_preflight(ws, timeout_s=tmo)
- if census:
- (ws.artifacts / "census.json").write_text(json.dumps(census, indent=1))
- gates_dir = ws.artifacts / "gates"
- gates_dir.mkdir(exist_ok=True)
- (gates_dir / "scene_probe.json").write_text(probe.model_dump_json(indent=1))
- (gates_dir / "shader_preflight.json").write_text(shaders.model_dump_json(indent=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,
- language=self.language.value,
- glb_path=None,
- extra_paths={
- "census": str(ws.artifacts / "census.json"),
- "scene_probe": str(gates_dir / "scene_probe.json"),
- "shader_preflight": str(gates_dir / "shader_preflight.json"),
- },
- 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,
- duration_ms=int((time.time() - t0) * 1000),
- census=census,
- )
- (ws.artifacts / "build.json").write_text(json.dumps(res.model_dump(mode="json"), indent=1))
- return res
-
- def contract_doc(self) -> str:
- p = _PROMPTS / "contract.md"
- if p.is_file():
- return p.read_text()
- return (_HERE / "CONTRACT.md").read_text()
-
- def cookbook_path(self) -> Path:
- return _PROMPTS / "cookbook.md"
-
-
-def _probe_and_preflight(ws: Workspace, *, timeout_s: float) -> tuple[GateReport, GateReport, dict]:
- """One ``probe_scene.mjs --compile`` run → (scene_probe, shader_preflight, census).
-
- The driver boots the scene once and runs both stages on the same page;
- when the scene never boots the preflight is skipped, matching the old
- two-call behaviour (a failed-empty shader gate).
- """
- from codeverse.contracts.artifacts import GateFinding
- from codeverse.spatial.probes import PROBE_GATE, SHADER_GATE, probe_report, shader_report
- from codeverse.spatial.render_scene import SceneRenderError, run_scene_script
-
- t0 = time.time()
- args = [
- "--ws", str(ws.root), "--compile",
- "--out", str(ws.artifacts / "scene_probe.json"),
- "--shaders-out", str(ws.artifacts / "shader_preflight.json"),
- "--timeout-ms", str(int(timeout_s * 1000)),
- ]
- try:
- res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)
- except SceneRenderError as e:
- dur = int((time.time() - t0) * 1000)
- finding = GateFinding(gate=PROBE_GATE, severity=Severity.ERROR, target="src/scene.js",
- message=f"scene probe could not run: {e}"[:1500],
- fix_hint="this is a harness/driver failure, not your code; retry or report",
- data={"harness_failure": True})
- return (GateReport(gate=PROBE_GATE, passed=False, findings=[finding], duration_ms=dur),
- GateReport(gate=SHADER_GATE, passed=False, findings=[]), {})
- dur = int((time.time() - t0) * 1000)
- probe, census = probe_report(res.summary, duration_ms=dur)
- rep = res.summary.get("shader_report") or {}
- if not rep or rep.get("skipped"):
- shaders = GateReport(gate=SHADER_GATE, passed=False, findings=[])
- else:
- shaders = shader_report(rep, duration_ms=int(rep.get("duration_ms") or 0))
- return probe, shaders, census
-
-
-def _summary_text(probe: GateReport, shaders: GateReport) -> str:
- lines = [f"scene_probe: {'ok' if probe.passed else 'FAILED'} ({len(probe.errors)} errors)"]
- lines += [f" - {f.target or ''}: {f.message}"[:400] for f in probe.findings if f.severity != Severity.INFO][:12]
- lines.append(f"shader_preflight: {'ok' if shaders.passed else 'FAILED'} ({len(shaders.errors)} errors)")
- 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/codeverse/languages/scene_threejs/skeleton.py b/harness/codeverse/languages/scene_threejs/skeleton.py
deleted file mode 100644
index 5b770637..00000000
--- a/harness/codeverse/languages/scene_threejs/skeleton.py
+++ /dev/null
@@ -1,209 +0,0 @@
-"""Starter files for ``scene_threejs`` workspaces.
-
-Without a plan: the complete example scene from ``starter/src`` (ground + sky
-gradient shader + instanced pine trees + animated windmill/lantern + GLSL water)
-— a concrete, working pattern the agent can run immediately.
-
-With a ``ScenePlan``: the same env/shader/asset pattern files plus one stub per
-planned zone (named group, plan bbox + contents in comments, a seated
-placeholder of each listed asset), one stub per ``threejs`` asset (blockout box
-at the planned size), GLB preloading for ``blender_glb`` assets, and a
-``src/scene.js`` wired to all zones with the plan's cameras.
-"""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-
-from codeverse.contracts.plan import AssetPlan, Plan, ScenePlan, ZonePlan
-from codeverse.conventions import to_pascal, to_snake
-from codeverse.workspace import Workspace
-
-STARTER_DIR = Path(__file__).resolve().parent / "starter" / "src"
-#: pattern files copied verbatim in plan mode (shown as reusable examples)
-PATTERN_FILES = ("shaders/sky.js", "shaders/water.js", "assets/pine_tree.js", "assets/windmill.js")
-
-
-def _write(path: Path, text: str, written: list[Path]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(text)
- written.append(path)
-
-
-def write_example(ws: Workspace) -> list[Path]:
- """Copy the full example scene into ws.src (overwrites).
-
- Raises when the starter tree is not there: rglob over a missing directory yields
- nothing, so this used to write ZERO files and report success — which is exactly what
- a non-editable (wheel) install produced before the starter tree was added to
- package-data, and it surfaced much later as an empty scene rather than a bad install.
- """
- if not STARTER_DIR.is_dir():
- raise FileNotFoundError(
- f"scene_threejs starter tree missing: {STARTER_DIR} — this install has no package data "
- f"(a non-editable install needs [tool.setuptools.package-data] to ship languages/**/starter/**/*)")
- written: list[Path] = []
- for src in sorted(STARTER_DIR.rglob("*.js")):
- rel = src.relative_to(STARTER_DIR)
- _write(ws.src / rel, src.read_text(), written)
- if not written:
- raise FileNotFoundError(f"scene_threejs starter tree at {STARTER_DIR} contains no .js files")
- return written
-
-
-def _env_for_plan(plan: ScenePlan) -> str:
- text = (STARTER_DIR / "env.js").read_text()
- ex = plan.bounds.extents
- span = max(ex[0], ex[2], 40.0)
- ground = int(max(120, span * 2.5))
- fog_near, fog_far = int(span * 0.8), int(max(span * 3.0, 200))
- text = re.sub(r"export const GROUND_SIZE = \d+;", f"export const GROUND_SIZE = {ground};", text)
- text = re.sub(r"const FOG_NEAR = \d+, FOG_FAR = \d+;", f"const FOG_NEAR = {fog_near}, FOG_FAR = {fog_far};", text)
- text = re.sub(r"const SKY_RADIUS = \d+;", f"const SKY_RADIUS = {int(max(600, ground * 3))};", text)
- header = (
- f"// ENV PLAN: {plan.environment.strip()}\n"
- f"// setting: {plan.setting.strip()} mood: {plan.mood.strip()}\n"
- f"// bounds: centre {tuple(round(c, 1) for c in plan.bounds.center)} extents {tuple(round(e, 1) for e in ex)} m\n"
- "// Rewrite the ground/sky/fog/sun below to match the plan; keep buildEnv/heightAt exports.\n"
- )
- return header + text
-
-
-def _asset_stub(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)
- return f'''// src/assets/{snake}.js — asset "{pascal}": {a.description.strip()}
-// approx size {w:g} x {h:g} x {d:g} m (w x h x d); expected instances: ~{a.instances_hint}
-// CONTRACT: export function build{pascal}(THREE) → THREE.Group, origin at the base (y = 0), +Y up, +Z front, meters.
-// Build it from several parts with distinct materials (see assets/pine_tree.js, assets/windmill.js);
-// for many instances also export {snake}Parts(THREE) → [{{ geometry, material, castShadow }}].
-import * as THREE from 'three';
-
-export function build{pascal}(T = THREE) {{
- const g = new T.Group();
- g.name = '{pascal}';
- // PLACEHOLDER blockout at the planned size — REPLACE with real construction.
- const box = new T.Mesh(new T.BoxGeometry({w:g}, {h:g}, {d:g}), new T.MeshStandardMaterial({{ color: 0x9a9a9a, roughness: 0.8 }}));
- box.position.y = {h / 2:g};
- box.castShadow = box.receiveShadow = true;
- g.add(box);
- return g;
-}}
-'''
-
-
-def _zone_stub(z: ZonePlan, assets: dict[str, AssetPlan]) -> str:
- snake, pascal = to_snake(z.name), to_pascal(z.name)
- c, e = z.bbox.center, z.bbox.extents
- imports, places = [], []
- for i, name in enumerate(z.contents):
- a = assets.get(to_snake(name))
- if a is None:
- continue
- asn, asp = to_snake(a.name), to_pascal(a.name)
- ox = (-e[0] / 4 + (i % 3) * e[0] / 4) if len(z.contents) > 1 else 0.0
- oz = (-e[2] / 4 + (i // 3) * e[2] / 4) if len(z.contents) > 3 else 0.0
- x, zz = round(c[0] + ox, 2), round(c[2] + oz, 2)
- if a.kind == "threejs":
- imports.append(f"import {{ build{asp} }} from '../assets/{asn}.js';")
- places.append(f" place(build{asp}(THREE), {x}, {zz});")
- else:
- places.append(
- f" if (ctx.assets && ctx.assets.{asn}) place(ctx.assets.{asn}.clone(), {x}, {zz});"
- f" // GLB built in Blender → public/assets/{asn}.glb (preloaded by scene.js)"
- )
- imp = "\n".join(imports)
- body = "\n".join(places) if places else " // TODO: build this zone's content here (use ctx.heightAt to seat objects)."
- return f'''// src/zones/{snake}.js — zone "{pascal}": {z.description.strip()}
-// PLAN bbox: centre ({c[0]:g}, {c[1]:g}, {c[2]:g}) extents ({e[0]:g} x {e[1]:g} x {e[2]:g}) m. Contents: {", ".join(z.contents) or "-"}
-// CONTRACT: export function build(ctx) → THREE.Group named '{pascal}'. ctx = {{ THREE, scene, renderer, loaders, env, heightAt, assets }}
-// • seat objects on the ground with ctx.heightAt(x, z); keep everything inside the plan bbox
-// • repeats → THREE.InstancedMesh (see the pattern in assets/pine_tree.js: <asset>Parts(THREE))
-// • animation → zone.userData.update = (t, dt) => {{ ... }} (scene.js fans update() out to every zone)
-import * as THREE from 'three';
-{imp}
-
-export function build(ctx) {{
- const {{ heightAt }} = ctx;
- const zone = new THREE.Group();
- zone.name = '{pascal}';
- const place = (obj, x, z, ry = 0) => {{ obj.position.set(x, heightAt(x, z), z); obj.rotation.y = ry; zone.add(obj); return obj; }};
-{body}
- zone.userData.update = (t, dt) => {{ /* animate zone elements here */ }};
- return zone;
-}}
-'''
-
-
-def _scene_for_plan(plan: ScenePlan) -> str:
- zones = [(to_snake(z.name), to_pascal(z.name)) for z in plan.zones]
- glbs = [to_snake(a.name) for a in plan.assets if a.kind == "blender_glb"]
- zone_imports = "\n".join(f"import {{ build as build{p} }} from './zones/{s}.js';" for s, p in zones)
- zone_calls = ", ".join(f"build{p}(ctx)" for _, p in zones)
- cams = ",\n".join(
- f" {{ name: '{to_snake(c.name)}', position: [{c.position[0]:g}, {c.position[1]:g}, {c.position[2]:g}], "
- f"lookAt: [{c.look_at[0]:g}, {c.look_at[1]:g}, {c.look_at[2]:g}], fov: {c.fov:g} }}"
- + (f" // {c.purpose}" if c.purpose else "")
- for c in plan.cameras[:6]
- )
- glb_block = ""
- if glbs:
- files = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
- glb_block = f'''
- // Blender-built assets (public/assets/*.glb) are preloaded once; zones clone ctx.assets.<name>.
- const assetFiles = {{ {files} }};
- const assets = {{}};
- for (const [key, url] of Object.entries(assetFiles)) {{
- try {{ assets[key] = (await loaders.gltf.loadAsync(url)).scene; }}
- catch (e) {{ console.warn(`[assets] missing ${{url}} (${{e && e.message}}) — build it with Blender into public/assets/`); }}
- }}
- ctx.assets = assets;
-'''
- async_kw = "async " if glbs else ""
- header = (STARTER_DIR / "scene.js").read_text().split("import * as THREE")[0]
- return f'''{header}// PLAN: {plan.title} — {plan.summary.strip()}
-// setting: {plan.setting.strip()} animation: {"; ".join(plan.animation) or "-"}
-import * as THREE from 'three';
-import {{ buildEnv, heightAt, SUN_AZIMUTH_DEG }} from './env.js';
-{zone_imports}
-
-export {async_kw}function createScene({{ THREE: T = THREE, renderer, loaders }}) {{
- const scene = new THREE.Scene();
- const ctx = {{ THREE, scene, renderer, loaders, heightAt, sunAzimuthDeg: SUN_AZIMUTH_DEG, assets: {{}} }};
- const env = buildEnv(ctx);
- ctx.env = env;
-{glb_block}
- const zones = [{zone_calls}];
- for (const z of zones) scene.add(z);
-
- const cameras = [
-{cams}
- ];
-
- function update(t, dt) {{
- if (env.update) env.update(t, dt);
- for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
- }}
- return {{ scene, cameras, update }};
-}}
-'''
-
-
-def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
- """Write starter files into ``ws.src``; returns the written paths."""
- if plan is None or not isinstance(plan, ScenePlan):
- return write_example(ws)
- written: list[Path] = []
- for rel in PATTERN_FILES:
- _write(ws.src / rel, (STARTER_DIR / rel).read_text(), written)
- _write(ws.src / "env.js", _env_for_plan(plan), written)
- assets = {to_snake(a.name): a for a in plan.assets}
- for a in plan.assets:
- if a.kind == "threejs":
- _write(ws.src / "assets" / f"{to_snake(a.name)}.js", _asset_stub(a), written)
- for z in plan.zones:
- _write(ws.src / "zones" / f"{to_snake(z.name)}.js", _zone_stub(z, assets), written)
- _write(ws.src / "scene.js", _scene_for_plan(plan), written)
- (ws.public / "assets").mkdir(parents=True, exist_ok=True)
- return written
diff --git a/harness/codeverse/languages/threejs/__init__.py b/harness/codeverse/languages/threejs/__init__.py
index 2648dae5..5a79ebb8 100644
--- a/harness/codeverse/languages/threejs/__init__.py
+++ b/harness/codeverse/languages/threejs/__init__.py
@@ -1,6 +1,490 @@
"""three.js (static object) language runtime: raw ESM authored by the agent,
GLB export + census by ``runtime_js/export_glb.mjs``."""
-from codeverse.languages.threejs.runtime import ThreeJsRuntime
+from __future__ import annotations
-__all__ = ["ThreeJsRuntime"]
+import json
+import re
+import time
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.plan import Plan, StaticPlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.languages._js_lint import ImportKind, ImportVerdict, check_imports
+from codeverse.languages._js_lint import (
+ node_check_syntax as check_syntax, # module-level name: tests monkeypatch it
+)
+from codeverse.proc import read_json_or_none
+from codeverse.prompts import PROMPTS_DIR, load_text
+from codeverse.spatial.node import NodeError, NodeResult, run_node, runtime_js_dir
+from codeverse.workspace import Workspace
+
+# ===================================================================== templates
+# (merged from codeverse/languages/threejs/templates.py, 2026-08-28)
+PACKAGE_JSON = '{ "type": "module", "private": true }\n'
+
+OBJECT_HEADER = """\
+// {object_name} — three.js static object (raw ESM). Harness contract:
+// export function build(THREE) -> THREE.Group (root.name = object name)
+// Y up, +Z front, meters; object stands on y=0, footprint centred on the Y axis.
+// Parts live in ./parts/<snake>.js, each `export function build<Pascal>(THREE)`
+// returning a Group already at its WORLD pose. object.js only assembles.
+// Optional idle animation: root.userData.tick = (t, dt) => {{ ... }}
+// Allowed imports: 'three', 'three/addons/...', relative './'. No network, no DOM.
+import * as THREE from 'three';
+{imports}
+
+export function build(THREE_) {{
+ const root = new THREE.Group();
+ root.name = '{object_name}';
+{adds}
+ return root;
+}}
+"""
+
+PART_TEMPLATE = """\
+// Part: {pascal} ({role})
+// {description}
+// Plan bbox (world, meters): centre {center} extents {extents}{material_line}
+// Contract: export function build{pascal}(THREE) -> THREE.Group named '{pascal}', at WORLD pose.
+// Y up, +Z front. Use real sizes in meters. Name every mesh. No lights/cameras/renderers.
+import * as THREE from 'three';
+import {{ RoundedBoxGeometry }} from 'three/addons/geometries/RoundedBoxGeometry.js';
+
+export function build{pascal}(THREE_) {{
+ const group = new THREE.Group();
+ group.name = '{pascal}';
+
+ // ---- PLACEHOLDER (replace with real construction; keep the group name) ----
+ // A rounded box filling the planned bbox. Copyable recipes:
+ // box: new THREE.BoxGeometry(w, h, d)
+ // bevelled: new RoundedBoxGeometry(w, h, d, 4, Math.min(w, h, d) * 0.08)
+ // cylinder: new THREE.CylinderGeometry(rTop, rBottom, h, 32)
+ // lathe: new THREE.LatheGeometry(points /* Vector2[] (x=radius, y=height) */, 48)
+ // extrude w/ bevel:
+ // const shape = new THREE.Shape(); shape.moveTo(-w/2, -d/2); shape.lineTo(w/2, -d/2);
+ // shape.lineTo(w/2, d/2); shape.lineTo(-w/2, d/2); shape.closePath();
+ // const geo = new THREE.ExtrudeGeometry(shape, {{ depth: h, bevelEnabled: true,
+ // bevelThickness: 0.004, bevelSize: 0.004, bevelSegments: 3 }});
+ // geo.rotateX(-Math.PI / 2); // extrude along +Y instead of +Z
+ // merge many: import {{ mergeGeometries }} from 'three/addons/utils/BufferGeometryUtils.js';
+ const size = [{ex}, {ey}, {ez}];
+ const geometry = new RoundedBoxGeometry(size[0], size[1], size[2], 3, Math.min(...size) * 0.08);
+ const material = new THREE.MeshStandardMaterial({{ color: {color}, roughness: 0.6, metalness: 0.05 }});
+ const mesh = new THREE.Mesh(geometry, material);
+ mesh.name = '{pascal}Body';
+ mesh.position.set({cx}, {cy}, {cz}); // world pose (bbox centre)
+ group.add(mesh);
+ // ---- END PLACEHOLDER ----
+
+ return group;
+}}
+"""
+
+PLACEHOLDER_COLORS = ("0x9aa5b1", "0xb08968", "0x7f8c8d", "0xc0a080", "0x6c7a89", "0xa0522d", "0x8fa3ad", "0xbfa27a")
+
+
+# ===================================================================== contract
+# (merged from codeverse/languages/threejs/contract.py, 2026-08-28)
+CONTRACT_FALLBACK = """\
+# three.js static-object contract (raw ESM, no SDK)
+
+Files (all under `src/`):
+* `src/parts/<snake_name>.js` — one file per part:
+ `export function build<PascalName>(THREE) { ...; return group; }`
+ The returned `THREE.Group` is named `<PascalName>` and already sits at its WORLD pose
+ (no re-positioning happens in object.js).
+* `src/object.js` — `export function build(THREE) { ... return root; }` imports every part
+ builder, adds each part group to one root `THREE.Group` whose `.name` is the object name,
+ and returns it. Optional: `root.userData.tick = (t, dt) => { ... }` for idle animation.
+
+Frame & units: Y is UP, +Z is the FRONT (towards the default camera), +X is the right.
+Meters. The object stands on the ground: lowest point at y = 0, footprint centred on
+the Y axis. Real-world sizes (a chair seat is ~0.45 m high, not 45).
+
+Imports allowed: `import * as THREE from 'three'`, `three/addons/...` (e.g.
+`three/addons/utils/BufferGeometryUtils.js`, `three/addons/geometries/RoundedBoxGeometry.js`),
+and relative `./` files inside `src/`. Nothing else: no CDN/http URLs, no npm packages,
+no `fetch`, no `document`/`window`, no WebGLRenderer/cameras/lights/scenes in object code —
+the harness renders and exports for you.
+
+Geometry & materials: BufferGeometry only; `MeshStandardMaterial`/`MeshPhysicalMaterial`
+with explicit `color`, `roughness`, `metalness`. Textures are NOT exportable from node —
+use materials and vertex detail. Every mesh gets a meaningful `.name`. Keep total
+triangles well under 600k. Parts must physically touch (no floating pieces) and must not
+interpenetrate visibly.
+
+Build: the harness runs `build(THREE)` in node, validates the group (≥1 mesh, finite
+bbox, no NaN), calls an optional exported `selfcheck(THREE, root)` (a throw fails the
+build with your message), bakes `InstancedMesh` copies into named meshes, and exports
+`artifacts/object.glb` with one named node per part — exactly where you placed it (no
+automatic drop-to-ground / re-centring; off-placement is warned and gated instead).
+"""
+
+
+# ===================================================================== lint
+# (merged from codeverse/languages/threejs/lint.py, 2026-08-28)
+GATE = "lint:threejs"
+
+_EXPORT_BUILD_RE = re.compile(r"\bexport\s+(?:async\s+)?function\s+(build[A-Za-z0-9_]*)\s*\(")
+_EXPORT_CONST_BUILD_RE = re.compile(r"\bexport\s+(?:const|let|var)\s+(build[A-Za-z0-9_]*)\s*=")
+_EXPORT_LIST_RE = re.compile(r"\bexport\s*\{([^}]*)\}")
+# strings and comments in ONE alternation so a '//' inside a string is not a comment
+_TOKEN_RE = re.compile(
+ r"""'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`|//[^\n]*|/\*.*?\*/""", re.S
+)
+
+# token -> (severity, message, fix hint)
+_FORBIDDEN: dict[str, tuple[Severity, str, str]] = {
+ r"\bfetch\s*\(": (Severity.ERROR, "network access (fetch) is not allowed in object code", "build geometry procedurally; no downloads"),
+ r"\bXMLHttpRequest\b": (Severity.ERROR, "network access (XMLHttpRequest) is not allowed", "remove it"),
+ r"\bWebSocket\b": (Severity.ERROR, "network access (WebSocket) is not allowed", "remove it"),
+ r"\bdocument\b": (Severity.ERROR, "DOM access (document) is not available: code runs in node", "remove DOM/canvas usage; no textures"),
+ r"\bwindow\b": (Severity.ERROR, "DOM access (window) is not available: code runs in node", "remove it"),
+ r"\bnavigator\b": (Severity.ERROR, "navigator is not available in node", "remove it"),
+ r"\blocalStorage\b": (Severity.ERROR, "localStorage is not available", "remove it"),
+ r"\brequire\s*\(": (Severity.ERROR, "CommonJS require() is not allowed; use ESM imports of 'three' only", "import * as THREE from 'three'"),
+ r"\bprocess\.": (Severity.ERROR, "node process access is not allowed in object code", "remove it"),
+ r"\beval\s*\(": (Severity.ERROR, "eval is not allowed", "remove it"),
+ r"\bWebGLRenderer\b": (Severity.ERROR, "do not create renderers: the harness renders", "return the Group from build(THREE); delete renderer code"),
+ r"\brequestAnimationFrame\b": (Severity.ERROR, "no render loops: put idle motion in root.userData.tick = (t, dt) => {}", "move per-frame logic into userData.tick"),
+ r"\bTextureLoader\b|\bImageLoader\b|\bFileLoader\b": (Severity.ERROR, "loaders/textures cannot be exported from node", "use MeshStandardMaterial colour/roughness/metalness instead"),
+ r"\bnew\s+THREE\.(?:Perspective|Orthographic)Camera\b": (Severity.WARN, "cameras in object code are ignored (harness owns the camera)", "delete it"),
+ r"\bnew\s+THREE\.[A-Za-z]*Light\s*\(": (Severity.WARN, "lights in object code are exported as extras and ignored by the harness lighting", "delete them"),
+ r"\bnew\s+THREE\.Scene\s*\(": (Severity.WARN, "do not build a Scene; return a Group", "replace Scene with Group"),
+}
+
+
+def _strip(src: str) -> str:
+ """Blank out comments and string contents (keeps newlines so line numbers survive)."""
+ def repl(m: re.Match[str]) -> str:
+ tok = m.group(0)
+ nl = "\n" * tok.count("\n")
+ return nl if tok.startswith("/") else '""' + nl
+ return _TOKEN_RE.sub(repl, src)
+
+
+def _line_of(text: str, pos: int) -> int:
+ return text.count("\n", 0, pos) + 1
+
+
+def _rel(ws: Workspace, p: Path) -> str:
+ try:
+ return str(p.relative_to(ws.root))
+ except ValueError:
+ return str(p)
+
+
+def list_sources(ws: Workspace) -> list[Path]:
+ if not ws.src.is_dir():
+ return []
+ return sorted(p for p in ws.src.rglob("*.js") if "node_modules" not in p.parts and not p.name.startswith("."))
+
+
+def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> set[Path]:
+ """Validate import specifiers; return the set of resolved relative targets."""
+ rel = _rel(ws, path)
+
+ def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
+ if v.kind is ImportKind.ESCAPES:
+ return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message=f"{rel}:{line}: import '{spec}' escapes src/", fix_hint="keep all files under src/")
+ if v.kind is ImportKind.MISSING:
+ assert v.target is not None
+ return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message=f"{rel}:{line}: imported file does not exist: '{spec}'",
+ fix_hint=f"create {_rel(ws, v.target)} or fix the path (extension '.js' is required)")
+ kind = "URL" if v.kind is ImportKind.URL else "package"
+ return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message=f"{rel}:{line}: import of {kind} '{spec}' is not allowed",
+ fix_hint="only 'three', 'three/addons/...' and relative './' imports are available")
+
+ new, targets = check_imports(src, path, ws.src, make_finding=make_finding)
+ findings.extend(new)
+ return targets
+
+
+def _lint_forbidden(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> None:
+ stripped = _strip(src)
+ rel = _rel(ws, path)
+ for pattern, (sev, msg, hint) in _FORBIDDEN.items():
+ m = re.search(pattern, stripped)
+ if m:
+ findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
+ message=f"{rel}:{_line_of(stripped, m.start())}: {msg}", fix_hint=hint))
+
+
+def _exports(src: str) -> set[str]:
+ names = {m.group(1) for m in _EXPORT_BUILD_RE.finditer(src)}
+ names |= {m.group(1) for m in _EXPORT_CONST_BUILD_RE.finditer(src)}
+ for m in _EXPORT_LIST_RE.finditer(src):
+ for item in m.group(1).split(","):
+ item = item.strip()
+ if not item:
+ continue
+ alias = item.split(" as ")[-1].strip()
+ if alias.startswith("build"):
+ names.add(alias)
+ return names
+
+
+def _load_plan(ws: Workspace) -> StaticPlan | None:
+ data = read_json_or_none(ws.plan_path)
+ if data is None or "parts" not in data or "joints" in data:
+ return None
+ try:
+ return StaticPlan.model_validate(data)
+ except ValueError:
+ return None
+
+
+def lint_workspace(ws: Workspace) -> GateReport:
+ """Run every static check and return the ``lint:threejs`` GateReport."""
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ node_bin = get_settings().binaries.node
+ entry = ws.src / "object.js"
+ sources = list_sources(ws)
+
+ if not entry.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target="src/object.js",
+ message="src/object.js is missing", fix_hint="create src/object.js with `export function build(THREE) { ... return root; }`"))
+
+ imported: set[Path] = set()
+ for path in sources:
+ src = path.read_text(errors="replace")
+ rel = _rel(ws, path)
+ syn = check_syntax(path, node_bin)
+ if syn is not None:
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message=f"{rel}:{syn.line or '?'}: {syn.message}", fix_hint="fix the syntax error at that line"))
+ continue # other checks are noise on a file that does not parse
+ imported |= _lint_imports(ws, path, src, findings)
+ _lint_forbidden(ws, path, src, findings)
+ exports = _exports(src)
+ if path == entry:
+ if "build" not in exports:
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message="src/object.js must `export function build(THREE)`", fix_hint="add `export function build(THREE) { const root = new THREE.Group(); ...; return root; }`"))
+ elif path.parent == ws.src / "parts":
+ expected = "build" + to_pascal(path.stem)
+ if expected not in exports:
+ sev = Severity.WARN if any(e != "build" for e in exports) else Severity.ERROR
+ findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
+ message=f"{rel}: expected `export function {expected}(THREE)` (found {sorted(exports) or 'no build export'})",
+ fix_hint=f"rename the export to {expected} or the file to parts/{to_snake(exports.pop()[5:]) if exports else path.stem}.js"))
+
+ part_files = [p for p in sources if p.parent == ws.src / "parts"]
+ for p in part_files:
+ if p not in imported:
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=_rel(ws, p),
+ message=f"{_rel(ws, p)} is not imported by any module (dead part file?)", fix_hint="import and add it in src/object.js or delete it"))
+
+ plan = _load_plan(ws)
+ if plan is not None:
+ for part in plan.parts:
+ pf = ws.src / "parts" / f"{to_snake(part.name)}.js"
+ if not pf.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=part.name,
+ message=f"planned part {part.name} has no file src/parts/{to_snake(part.name)}.js",
+ fix_hint=f"create it with `export function build{to_pascal(part.name)}(THREE)`"))
+ elif pf not in imported and entry.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=part.name,
+ message=f"planned part {part.name} is not assembled by src/object.js",
+ fix_hint=f"import {{ build{to_pascal(part.name)} }} from './parts/{to_snake(part.name)}.js' and root.add(...)"))
+
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+# ===================================================================== skeleton
+# (merged from codeverse/languages/threejs/skeleton.py, 2026-08-28)
+def part_file(ws: Workspace, part_name: str) -> Path:
+ """``src/parts/<snake>.js`` for a plan part name."""
+ return ws.src / "parts" / f"{to_snake(part_name)}.js"
+
+
+def _fmt(v: float) -> str:
+ return f"{float(v):.4g}"
+
+
+def render_part_stub(part, index: int) -> str:
+ """JS source of one placeholder part file."""
+ c, e = part.bbox.center, part.bbox.extents
+ material_line = f"\n// Material: {part.material}" if part.material else ""
+ return PART_TEMPLATE.format(
+ pascal=to_pascal(part.name),
+ role=part.role,
+ description=part.description.replace("\n", " "),
+ center=f"({_fmt(c[0])}, {_fmt(c[1])}, {_fmt(c[2])})",
+ extents=f"({_fmt(e[0])}, {_fmt(e[1])}, {_fmt(e[2])})",
+ material_line=material_line,
+ ex=_fmt(max(e[0], 0.001)),
+ ey=_fmt(max(e[1], 0.001)),
+ ez=_fmt(max(e[2], 0.001)),
+ cx=_fmt(c[0]),
+ cy=_fmt(c[1]),
+ cz=_fmt(c[2]),
+ color=PLACEHOLDER_COLORS[index % len(PLACEHOLDER_COLORS)],
+ )
+
+
+def render_object(plan: StaticPlan) -> str:
+ imports = "\n".join(
+ f"import {{ build{to_pascal(p.name)} }} from './parts/{to_snake(p.name)}.js';" for p in plan.parts
+ )
+ adds = "\n".join(f" root.add(build{to_pascal(p.name)}(THREE));" for p in plan.parts)
+ return OBJECT_HEADER.format(object_name=to_pascal(plan.object_name), imports=imports, adds=adds)
+
+
+def write_skeleton(ws: Workspace, plan: Plan, *, overwrite: bool = False) -> list[Path]:
+ """Write ``src/package.json``, ``src/object.js`` and ``src/parts/*.js``; return written paths.
+
+ Existing files are kept unless ``overwrite`` (so re-running on a refined
+ workspace never clobbers agent work).
+ """
+ if not isinstance(plan, StaticPlan):
+ raise TypeError(f"threejs skeleton needs a StaticPlan, got {type(plan).__name__}")
+ written: list[Path] = []
+ (ws.src / "parts").mkdir(parents=True, exist_ok=True)
+
+ def _put(path: Path, text: str) -> None:
+ if path.exists() and not overwrite:
+ return
+ path.write_text(text)
+ written.append(path)
+
+ _put(ws.src / "package.json", PACKAGE_JSON)
+ _put(ws.src / "object.js", render_object(plan))
+ for i, part in enumerate(plan.parts):
+ _put(part_file(ws, part.name), render_part_stub(part, i))
+ return written
+
+
+# ===================================================================== runtime
+# (merged from codeverse/languages/threejs/runtime.py, 2026-08-28)
+ENTRY = "src/object.js"
+GLB_NAME = "object.glb"
+CENSUS_NAME = "census.json"
+BUILD_JSON = "build.json"
+NODE_MEM_LIMIT_GB = 8.0 # RLIMIT_AS for the export process (geometry-bomb protection)
+
+
+class ThreeJsRuntime:
+ """LanguageRuntime for ``Language.THREEJS`` (raw ESM three.js, exported via node)."""
+
+ language = Language.THREEJS
+ entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.THREEJS], "src/parts/*.js")
+
+ # ------------------------------------------------------------------ contract
+ def contract_doc(self) -> str:
+ try:
+ return load_text("threejs/contract.md")
+ except FileNotFoundError:
+ return CONTRACT_FALLBACK
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "threejs" / "cookbook.md"
+
+ # ------------------------------------------------------------------ skeleton / lint
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ # ------------------------------------------------------------------ build
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ """Run ``runtime_js/export_glb.mjs`` on ``src/object.js`` → ``artifacts/object.glb``.
+
+ Never raises for agent-code failures: they come back as ``ok=False`` with
+ ``error_type/message/file/line`` and the stdout/stderr tails. Harness
+ misconfiguration (missing node, missing script) still raises.
+ """
+ settings = get_settings()
+ timeout_s = timeout_s or settings.limits.build_timeout_s
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ glb = ws.artifacts / GLB_NAME
+ census = ws.artifacts / CENSUS_NAME
+ # build.json is in the wipe too: the node-missing raise below returns before
+ # _write_build_json, and a stale ok:true build.json must not survive it
+ ws.stage_artifacts(GLB_NAME, CENSUS_NAME, BUILD_JSON, "export_error.json").invalidate()
+ self._ensure_module_type(ws)
+
+ t0 = time.time()
+ args = ["--ws", str(ws.root), "--entry", ENTRY, "--out", str(glb), "--census", str(census)]
+ try:
+ res = run_node(
+ runtime_js_dir() / "export_glb.mjs", args, cwd=ws.root, timeout_s=timeout_s,
+ three_hook=True, node_args=["--max-old-space-size=4096"], check=False,
+ mem_limit_gb=NODE_MEM_LIMIT_GB,
+ )
+ except NodeError as e:
+ if e.result is None:
+ raise # harness problem (no node binary / script)
+ result = self._failure(e.result, "Timeout" if e.result.timed_out else "NodeError", str(e))
+ self._write_build_json(ws, result)
+ return result
+
+ if res.rc != 0 or not (res.last_json or {}).get("ok") or not glb.is_file():
+ result = self._from_error_record(res, ws)
+ else:
+ census_data: dict[str, Any] = {}
+ if census.is_file():
+ census_data = json.loads(census.read_text())
+ result = BuildResult(
+ ok=True, language=self.language.value, glb_path=str(glb),
+ stdout_tail=res.stdout_tail, stderr_tail=res.stderr_tail,
+ duration_ms=int((time.time() - t0) * 1000), census=census_data,
+ extra_paths={"census": str(census)},
+ )
+ self._write_build_json(ws, result)
+ return result
+
+ # ------------------------------------------------------------------ helpers
+ @staticmethod
+ def _ensure_module_type(ws: Workspace) -> None:
+ """``src/package.json`` {type: module} so ``.js`` files are parsed as ESM."""
+ ws.src.mkdir(parents=True, exist_ok=True)
+ pj = ws.src / "package.json"
+ if not pj.is_file():
+ pj.write_text(PACKAGE_JSON)
+
+ def _failure(self, res: NodeResult, etype: str, message: str) -> BuildResult:
+ return BuildResult(
+ ok=False, language=self.language.value, stdout_tail=res.stdout_tail, stderr_tail=res.stderr_tail,
+ error_type=etype, error_message=message[:2000], duration_ms=res.duration_ms,
+ )
+
+ def _from_error_record(self, res: NodeResult, ws: Workspace | None = None) -> BuildResult:
+ rec = res.last_json or {}
+ err = rec.get("error") if isinstance(rec.get("error"), dict) else None
+ if err is None:
+ tail = res.stderr_tail.strip().splitlines()
+ return self._failure(res, "ExportError", tail[-1] if tail else f"export_glb exited {res.rc} without an error record")
+ result = self._failure(res, str(err.get("type", "Error")), str(err.get("message", "")))
+ result.error_file = str(err.get("file", "") or self._part_file(ws, err.get("part")) or ("" if err.get("frames") else ENTRY))
+ result.error_line = err.get("line") if isinstance(err.get("line"), int) else None
+ result.census = {"frames": err.get("frames", []), "stack": err.get("stack", ""), "part": str(err.get("part", "") or "")}
+ return result
+
+ @staticmethod
+ def _part_file(ws: Workspace | None, part: object) -> str:
+ """``src/parts/<snake>.js`` for the plan part named in a validation error (when that file exists).
+
+ Contract errors raised by the exporter (NaN geometry, empty bbox) carry no src
+ frame — the throw site is export_glb.mjs — but name the offending part; the
+ naming convention (``conventions.to_snake``) turns that into the file to repair.
+ """
+ if ws is None or not isinstance(part, str) or not part.strip():
+ return ""
+ rel = Path("src") / "parts" / f"{to_snake(part)}.js"
+ return rel.as_posix() if (ws.root / rel).is_file() else ""
+
+ @staticmethod
+ def _write_build_json(ws: Workspace, result: BuildResult) -> None:
+ ws.write_json(ws.artifacts / BUILD_JSON, result)
diff --git a/harness/codeverse/languages/threejs/contract.py b/harness/codeverse/languages/threejs/contract.py
deleted file mode 100644
index a2a8fa63..00000000
--- a/harness/codeverse/languages/threejs/contract.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""Built-in fallback for the three.js authoring contract (prompts/threejs/contract.md wins)."""
-
-from __future__ import annotations
-
-CONTRACT_FALLBACK = """\
-# three.js static-object contract (raw ESM, no SDK)
-
-Files (all under `src/`):
-* `src/parts/<snake_name>.js` — one file per part:
- `export function build<PascalName>(THREE) { ...; return group; }`
- The returned `THREE.Group` is named `<PascalName>` and already sits at its WORLD pose
- (no re-positioning happens in object.js).
-* `src/object.js` — `export function build(THREE) { ... return root; }` imports every part
- builder, adds each part group to one root `THREE.Group` whose `.name` is the object name,
- and returns it. Optional: `root.userData.tick = (t, dt) => { ... }` for idle animation.
-
-Frame & units: Y is UP, +Z is the FRONT (towards the default camera), +X is the right.
-Meters. The object stands on the ground: lowest point at y = 0, footprint centred on
-the Y axis. Real-world sizes (a chair seat is ~0.45 m high, not 45).
-
-Imports allowed: `import * as THREE from 'three'`, `three/addons/...` (e.g.
-`three/addons/utils/BufferGeometryUtils.js`, `three/addons/geometries/RoundedBoxGeometry.js`),
-and relative `./` files inside `src/`. Nothing else: no CDN/http URLs, no npm packages,
-no `fetch`, no `document`/`window`, no WebGLRenderer/cameras/lights/scenes in object code —
-the harness renders and exports for you.
-
-Geometry & materials: BufferGeometry only; `MeshStandardMaterial`/`MeshPhysicalMaterial`
-with explicit `color`, `roughness`, `metalness`. Textures are NOT exportable from node —
-use materials and vertex detail. Every mesh gets a meaningful `.name`. Keep total
-triangles well under 600k. Parts must physically touch (no floating pieces) and must not
-interpenetrate visibly.
-
-Build: the harness runs `build(THREE)` in node, validates the group (≥1 mesh, finite
-bbox, no NaN), calls an optional exported `selfcheck(THREE, root)` (a throw fails the
-build with your message), bakes `InstancedMesh` copies into named meshes, and exports
-`artifacts/object.glb` with one named node per part — exactly where you placed it (no
-automatic drop-to-ground / re-centring; off-placement is warned and gated instead).
-"""
diff --git a/harness/codeverse/languages/threejs/lint.py b/harness/codeverse/languages/threejs/lint.py
deleted file mode 100644
index 6d27d5e7..00000000
--- a/harness/codeverse/languages/threejs/lint.py
+++ /dev/null
@@ -1,196 +0,0 @@
-"""Static lint for three.js static-object code (no execution of agent code).
-
-Checks: ESM syntax (``node --check``), allowed imports (``three``,
-``three/addons/*``, relative files that exist), forbidden browser/network/node
-APIs, the ``build`` / ``build<Pascal>`` entry points, and (when a plan exists)
-that every planned part has a file and is assembled by ``object.js``.
-"""
-
-from __future__ import annotations
-
-import re
-import time
-from pathlib import Path
-
-from codeverse.config import get_settings
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.contracts.plan import StaticPlan
-from codeverse.conventions import to_pascal, to_snake
-from codeverse.languages._js_lint import ImportKind, ImportVerdict, check_imports
-from codeverse.languages._js_lint import (
- node_check_syntax as check_syntax, # module-level name: tests monkeypatch it
-)
-from codeverse.proc import read_json_or_none
-from codeverse.workspace import Workspace
-
-GATE = "lint:threejs"
-
-_EXPORT_BUILD_RE = re.compile(r"\bexport\s+(?:async\s+)?function\s+(build[A-Za-z0-9_]*)\s*\(")
-_EXPORT_CONST_BUILD_RE = re.compile(r"\bexport\s+(?:const|let|var)\s+(build[A-Za-z0-9_]*)\s*=")
-_EXPORT_LIST_RE = re.compile(r"\bexport\s*\{([^}]*)\}")
-# strings and comments in ONE alternation so a '//' inside a string is not a comment
-_TOKEN_RE = re.compile(
- r"""'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`|//[^\n]*|/\*.*?\*/""", re.S
-)
-
-# token -> (severity, message, fix hint)
-_FORBIDDEN: dict[str, tuple[Severity, str, str]] = {
- r"\bfetch\s*\(": (Severity.ERROR, "network access (fetch) is not allowed in object code", "build geometry procedurally; no downloads"),
- r"\bXMLHttpRequest\b": (Severity.ERROR, "network access (XMLHttpRequest) is not allowed", "remove it"),
- r"\bWebSocket\b": (Severity.ERROR, "network access (WebSocket) is not allowed", "remove it"),
- r"\bdocument\b": (Severity.ERROR, "DOM access (document) is not available: code runs in node", "remove DOM/canvas usage; no textures"),
- r"\bwindow\b": (Severity.ERROR, "DOM access (window) is not available: code runs in node", "remove it"),
- r"\bnavigator\b": (Severity.ERROR, "navigator is not available in node", "remove it"),
- r"\blocalStorage\b": (Severity.ERROR, "localStorage is not available", "remove it"),
- r"\brequire\s*\(": (Severity.ERROR, "CommonJS require() is not allowed; use ESM imports of 'three' only", "import * as THREE from 'three'"),
- r"\bprocess\.": (Severity.ERROR, "node process access is not allowed in object code", "remove it"),
- r"\beval\s*\(": (Severity.ERROR, "eval is not allowed", "remove it"),
- r"\bWebGLRenderer\b": (Severity.ERROR, "do not create renderers: the harness renders", "return the Group from build(THREE); delete renderer code"),
- r"\brequestAnimationFrame\b": (Severity.ERROR, "no render loops: put idle motion in root.userData.tick = (t, dt) => {}", "move per-frame logic into userData.tick"),
- r"\bTextureLoader\b|\bImageLoader\b|\bFileLoader\b": (Severity.ERROR, "loaders/textures cannot be exported from node", "use MeshStandardMaterial colour/roughness/metalness instead"),
- r"\bnew\s+THREE\.(?:Perspective|Orthographic)Camera\b": (Severity.WARN, "cameras in object code are ignored (harness owns the camera)", "delete it"),
- r"\bnew\s+THREE\.[A-Za-z]*Light\s*\(": (Severity.WARN, "lights in object code are exported as extras and ignored by the harness lighting", "delete them"),
- r"\bnew\s+THREE\.Scene\s*\(": (Severity.WARN, "do not build a Scene; return a Group", "replace Scene with Group"),
-}
-
-
-def _strip(src: str) -> str:
- """Blank out comments and string contents (keeps newlines so line numbers survive)."""
- def repl(m: re.Match[str]) -> str:
- tok = m.group(0)
- nl = "\n" * tok.count("\n")
- return nl if tok.startswith("/") else '""' + nl
- return _TOKEN_RE.sub(repl, src)
-
-
-def _line_of(text: str, pos: int) -> int:
- return text.count("\n", 0, pos) + 1
-
-
-def _rel(ws: Workspace, p: Path) -> str:
- try:
- return str(p.relative_to(ws.root))
- except ValueError:
- return str(p)
-
-
-def list_sources(ws: Workspace) -> list[Path]:
- if not ws.src.is_dir():
- return []
- return sorted(p for p in ws.src.rglob("*.js") if "node_modules" not in p.parts and not p.name.startswith("."))
-
-
-def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> set[Path]:
- """Validate import specifiers; return the set of resolved relative targets."""
- rel = _rel(ws, path)
-
- def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
- if v.kind is ImportKind.ESCAPES:
- return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message=f"{rel}:{line}: import '{spec}' escapes src/", fix_hint="keep all files under src/")
- if v.kind is ImportKind.MISSING:
- assert v.target is not None
- return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message=f"{rel}:{line}: imported file does not exist: '{spec}'",
- fix_hint=f"create {_rel(ws, v.target)} or fix the path (extension '.js' is required)")
- kind = "URL" if v.kind is ImportKind.URL else "package"
- return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message=f"{rel}:{line}: import of {kind} '{spec}' is not allowed",
- fix_hint="only 'three', 'three/addons/...' and relative './' imports are available")
-
- new, targets = check_imports(src, path, ws.src, make_finding=make_finding)
- findings.extend(new)
- return targets
-
-
-def _lint_forbidden(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> None:
- stripped = _strip(src)
- rel = _rel(ws, path)
- for pattern, (sev, msg, hint) in _FORBIDDEN.items():
- m = re.search(pattern, stripped)
- if m:
- findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
- message=f"{rel}:{_line_of(stripped, m.start())}: {msg}", fix_hint=hint))
-
-
-def _exports(src: str) -> set[str]:
- names = {m.group(1) for m in _EXPORT_BUILD_RE.finditer(src)}
- names |= {m.group(1) for m in _EXPORT_CONST_BUILD_RE.finditer(src)}
- for m in _EXPORT_LIST_RE.finditer(src):
- for item in m.group(1).split(","):
- item = item.strip()
- if not item:
- continue
- alias = item.split(" as ")[-1].strip()
- if alias.startswith("build"):
- names.add(alias)
- return names
-
-
-def _load_plan(ws: Workspace) -> StaticPlan | None:
- data = read_json_or_none(ws.plan_path)
- if data is None or "parts" not in data or "joints" in data:
- return None
- try:
- return StaticPlan.model_validate(data)
- except ValueError:
- return None
-
-
-def lint_workspace(ws: Workspace) -> GateReport:
- """Run every static check and return the ``lint:threejs`` GateReport."""
- t0 = time.time()
- findings: list[GateFinding] = []
- node_bin = get_settings().binaries.node
- entry = ws.src / "object.js"
- sources = list_sources(ws)
-
- if not entry.is_file():
- findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target="src/object.js",
- message="src/object.js is missing", fix_hint="create src/object.js with `export function build(THREE) { ... return root; }`"))
-
- imported: set[Path] = set()
- for path in sources:
- src = path.read_text(errors="replace")
- rel = _rel(ws, path)
- syn = check_syntax(path, node_bin)
- if syn is not None:
- findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message=f"{rel}:{syn.line or '?'}: {syn.message}", fix_hint="fix the syntax error at that line"))
- continue # other checks are noise on a file that does not parse
- imported |= _lint_imports(ws, path, src, findings)
- _lint_forbidden(ws, path, src, findings)
- exports = _exports(src)
- if path == entry:
- if "build" not in exports:
- findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message="src/object.js must `export function build(THREE)`", fix_hint="add `export function build(THREE) { const root = new THREE.Group(); ...; return root; }`"))
- elif path.parent == ws.src / "parts":
- expected = "build" + to_pascal(path.stem)
- if expected not in exports:
- sev = Severity.WARN if any(e != "build" for e in exports) else Severity.ERROR
- findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
- message=f"{rel}: expected `export function {expected}(THREE)` (found {sorted(exports) or 'no build export'})",
- fix_hint=f"rename the export to {expected} or the file to parts/{to_snake(exports.pop()[5:]) if exports else path.stem}.js"))
-
- part_files = [p for p in sources if p.parent == ws.src / "parts"]
- for p in part_files:
- if p not in imported:
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=_rel(ws, p),
- message=f"{_rel(ws, p)} is not imported by any module (dead part file?)", fix_hint="import and add it in src/object.js or delete it"))
-
- plan = _load_plan(ws)
- if plan is not None:
- for part in plan.parts:
- pf = ws.src / "parts" / f"{to_snake(part.name)}.js"
- if not pf.is_file():
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=part.name,
- message=f"planned part {part.name} has no file src/parts/{to_snake(part.name)}.js",
- fix_hint=f"create it with `export function build{to_pascal(part.name)}(THREE)`"))
- elif pf not in imported and entry.is_file():
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=part.name,
- message=f"planned part {part.name} is not assembled by src/object.js",
- fix_hint=f"import {{ build{to_pascal(part.name)} }} from './parts/{to_snake(part.name)}.js' and root.add(...)"))
-
- passed = not any(f.severity == Severity.ERROR for f in findings)
- return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/languages/threejs/runtime.py b/harness/codeverse/languages/threejs/runtime.py
deleted file mode 100644
index 813f16b4..00000000
--- a/harness/codeverse/languages/threejs/runtime.py
+++ /dev/null
@@ -1,143 +0,0 @@
-"""ThreeJsRuntime: skeleton → lint → build (node GLTFExporter) for static objects."""
-
-from __future__ import annotations
-
-import json
-import time
-from pathlib import Path
-from typing import Any
-
-from codeverse.config import get_settings
-from codeverse.contracts.artifacts import BuildResult, GateReport
-from codeverse.contracts.common import ENTRY_FILE, Language
-from codeverse.contracts.plan import Plan
-from codeverse.conventions import to_snake
-from codeverse.languages.threejs.contract import CONTRACT_FALLBACK
-from codeverse.languages.threejs.lint import lint_workspace
-from codeverse.languages.threejs.skeleton import write_skeleton
-from codeverse.languages.threejs.templates import PACKAGE_JSON
-from codeverse.prompts import PROMPTS_DIR, load_text
-from codeverse.spatial.node import NodeError, NodeResult, run_node, runtime_js_dir
-from codeverse.workspace import Workspace
-
-ENTRY = "src/object.js"
-GLB_NAME = "object.glb"
-CENSUS_NAME = "census.json"
-BUILD_JSON = "build.json"
-NODE_MEM_LIMIT_GB = 8.0 # RLIMIT_AS for the export process (geometry-bomb protection)
-
-
-class ThreeJsRuntime:
- """LanguageRuntime for ``Language.THREEJS`` (raw ESM three.js, exported via node)."""
-
- language = Language.THREEJS
- entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.THREEJS], "src/parts/*.js")
-
- # ------------------------------------------------------------------ contract
- def contract_doc(self) -> str:
- try:
- return load_text("threejs/contract.md")
- except FileNotFoundError:
- return CONTRACT_FALLBACK
-
- def cookbook_path(self) -> Path:
- return PROMPTS_DIR / "threejs" / "cookbook.md"
-
- # ------------------------------------------------------------------ skeleton / lint
- def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
- return write_skeleton(ws, plan)
-
- def lint(self, ws: Workspace) -> GateReport:
- return lint_workspace(ws)
-
- # ------------------------------------------------------------------ build
- def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
- """Run ``runtime_js/export_glb.mjs`` on ``src/object.js`` → ``artifacts/object.glb``.
-
- Never raises for agent-code failures: they come back as ``ok=False`` with
- ``error_type/message/file/line`` and the stdout/stderr tails. Harness
- misconfiguration (missing node, missing script) still raises.
- """
- settings = get_settings()
- timeout_s = timeout_s or settings.limits.build_timeout_s
- ws.artifacts.mkdir(parents=True, exist_ok=True)
- glb = ws.artifacts / GLB_NAME
- census = ws.artifacts / CENSUS_NAME
- # build.json is in the wipe too: the node-missing raise below returns before
- # _write_build_json, and a stale ok:true build.json must not survive it
- ws.stage_artifacts(GLB_NAME, CENSUS_NAME, BUILD_JSON, "export_error.json").invalidate()
- self._ensure_module_type(ws)
-
- t0 = time.time()
- args = ["--ws", str(ws.root), "--entry", ENTRY, "--out", str(glb), "--census", str(census)]
- try:
- res = run_node(
- runtime_js_dir() / "export_glb.mjs", args, cwd=ws.root, timeout_s=timeout_s,
- three_hook=True, node_args=["--max-old-space-size=4096"], check=False,
- mem_limit_gb=NODE_MEM_LIMIT_GB,
- )
- except NodeError as e:
- if e.result is None:
- raise # harness problem (no node binary / script)
- result = self._failure(e.result, "Timeout" if e.result.timed_out else "NodeError", str(e))
- self._write_build_json(ws, result)
- return result
-
- if res.rc != 0 or not (res.last_json or {}).get("ok") or not glb.is_file():
- result = self._from_error_record(res, ws)
- else:
- census_data: dict[str, Any] = {}
- if census.is_file():
- census_data = json.loads(census.read_text())
- result = BuildResult(
- ok=True, language=self.language.value, glb_path=str(glb),
- stdout_tail=res.stdout_tail, stderr_tail=res.stderr_tail,
- duration_ms=int((time.time() - t0) * 1000), census=census_data,
- extra_paths={"census": str(census)},
- )
- self._write_build_json(ws, result)
- return result
-
- # ------------------------------------------------------------------ helpers
- @staticmethod
- def _ensure_module_type(ws: Workspace) -> None:
- """``src/package.json`` {type: module} so ``.js`` files are parsed as ESM."""
- ws.src.mkdir(parents=True, exist_ok=True)
- pj = ws.src / "package.json"
- if not pj.is_file():
- pj.write_text(PACKAGE_JSON)
-
- def _failure(self, res: NodeResult, etype: str, message: str) -> BuildResult:
- return BuildResult(
- ok=False, language=self.language.value, stdout_tail=res.stdout_tail, stderr_tail=res.stderr_tail,
- error_type=etype, error_message=message[:2000], duration_ms=res.duration_ms,
- )
-
- def _from_error_record(self, res: NodeResult, ws: Workspace | None = None) -> BuildResult:
- rec = res.last_json or {}
- err = rec.get("error") if isinstance(rec.get("error"), dict) else None
- if err is None:
- tail = res.stderr_tail.strip().splitlines()
- return self._failure(res, "ExportError", tail[-1] if tail else f"export_glb exited {res.rc} without an error record")
- result = self._failure(res, str(err.get("type", "Error")), str(err.get("message", "")))
- result.error_file = str(err.get("file", "") or self._part_file(ws, err.get("part")) or ("" if err.get("frames") else ENTRY))
- result.error_line = err.get("line") if isinstance(err.get("line"), int) else None
- result.census = {"frames": err.get("frames", []), "stack": err.get("stack", ""), "part": str(err.get("part", "") or "")}
- return result
-
- @staticmethod
- def _part_file(ws: Workspace | None, part: object) -> str:
- """``src/parts/<snake>.js`` for the plan part named in a validation error (when that file exists).
-
- Contract errors raised by the exporter (NaN geometry, empty bbox) carry no src
- frame — the throw site is export_glb.mjs — but name the offending part; the
- naming convention (``conventions.to_snake``) turns that into the file to repair.
- """
- if ws is None or not isinstance(part, str) or not part.strip():
- return ""
- rel = Path("src") / "parts" / f"{to_snake(part)}.js"
- return rel.as_posix() if (ws.root / rel).is_file() else ""
-
- @staticmethod
- def _write_build_json(ws: Workspace, result: BuildResult) -> None:
- ws.write_json(ws.artifacts / BUILD_JSON, result)
diff --git a/harness/codeverse/languages/threejs/skeleton.py b/harness/codeverse/languages/threejs/skeleton.py
deleted file mode 100644
index 2f8c1783..00000000
--- a/harness/codeverse/languages/threejs/skeleton.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""Starter files for a three.js static object from a StaticPlan.
-
-Every part gets a stub that already BUILDS (a rounded-box placeholder at the
-planned bbox) so the skeleton exports and renders before the agent touches it;
-the agent replaces placeholders part by part and the gates show what is left.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from codeverse.contracts.plan import Plan, StaticPlan
-from codeverse.conventions import to_pascal, to_snake
-from codeverse.languages.threejs.templates import (
- OBJECT_HEADER,
- PACKAGE_JSON,
- PART_TEMPLATE,
- PLACEHOLDER_COLORS,
-)
-from codeverse.workspace import Workspace
-
-
-def part_file(ws: Workspace, part_name: str) -> Path:
- """``src/parts/<snake>.js`` for a plan part name."""
- return ws.src / "parts" / f"{to_snake(part_name)}.js"
-
-
-def _fmt(v: float) -> str:
- return f"{float(v):.4g}"
-
-
-def render_part_stub(part, index: int) -> str:
- """JS source of one placeholder part file."""
- c, e = part.bbox.center, part.bbox.extents
- material_line = f"\n// Material: {part.material}" if part.material else ""
- return PART_TEMPLATE.format(
- pascal=to_pascal(part.name),
- role=part.role,
- description=part.description.replace("\n", " "),
- center=f"({_fmt(c[0])}, {_fmt(c[1])}, {_fmt(c[2])})",
- extents=f"({_fmt(e[0])}, {_fmt(e[1])}, {_fmt(e[2])})",
- material_line=material_line,
- ex=_fmt(max(e[0], 0.001)),
- ey=_fmt(max(e[1], 0.001)),
- ez=_fmt(max(e[2], 0.001)),
- cx=_fmt(c[0]),
- cy=_fmt(c[1]),
- cz=_fmt(c[2]),
- color=PLACEHOLDER_COLORS[index % len(PLACEHOLDER_COLORS)],
- )
-
-
-def render_object(plan: StaticPlan) -> str:
- imports = "\n".join(
- f"import {{ build{to_pascal(p.name)} }} from './parts/{to_snake(p.name)}.js';" for p in plan.parts
- )
- adds = "\n".join(f" root.add(build{to_pascal(p.name)}(THREE));" for p in plan.parts)
- return OBJECT_HEADER.format(object_name=to_pascal(plan.object_name), imports=imports, adds=adds)
-
-
-def write_skeleton(ws: Workspace, plan: Plan, *, overwrite: bool = False) -> list[Path]:
- """Write ``src/package.json``, ``src/object.js`` and ``src/parts/*.js``; return written paths.
-
- Existing files are kept unless ``overwrite`` (so re-running on a refined
- workspace never clobbers agent work).
- """
- if not isinstance(plan, StaticPlan):
- raise TypeError(f"threejs skeleton needs a StaticPlan, got {type(plan).__name__}")
- written: list[Path] = []
- (ws.src / "parts").mkdir(parents=True, exist_ok=True)
-
- def _put(path: Path, text: str) -> None:
- if path.exists() and not overwrite:
- return
- path.write_text(text)
- written.append(path)
-
- _put(ws.src / "package.json", PACKAGE_JSON)
- _put(ws.src / "object.js", render_object(plan))
- for i, part in enumerate(plan.parts):
- _put(part_file(ws, part.name), render_part_stub(part, i))
- return written
diff --git a/harness/codeverse/languages/threejs/templates.py b/harness/codeverse/languages/threejs/templates.py
deleted file mode 100644
index df56d966..00000000
--- a/harness/codeverse/languages/threejs/templates.py
+++ /dev/null
@@ -1,65 +0,0 @@
-"""String templates for the three.js skeleton (object.js + one stub per part)."""
-
-from __future__ import annotations
-
-PACKAGE_JSON = '{ "type": "module", "private": true }\n'
-
-OBJECT_HEADER = """\
-// {object_name} — three.js static object (raw ESM). Harness contract:
-// export function build(THREE) -> THREE.Group (root.name = object name)
-// Y up, +Z front, meters; object stands on y=0, footprint centred on the Y axis.
-// Parts live in ./parts/<snake>.js, each `export function build<Pascal>(THREE)`
-// returning a Group already at its WORLD pose. object.js only assembles.
-// Optional idle animation: root.userData.tick = (t, dt) => {{ ... }}
-// Allowed imports: 'three', 'three/addons/...', relative './'. No network, no DOM.
-import * as THREE from 'three';
-{imports}
-
-export function build(THREE_) {{
- const root = new THREE.Group();
- root.name = '{object_name}';
-{adds}
- return root;
-}}
-"""
-
-PART_TEMPLATE = """\
-// Part: {pascal} ({role})
-// {description}
-// Plan bbox (world, meters): centre {center} extents {extents}{material_line}
-// Contract: export function build{pascal}(THREE) -> THREE.Group named '{pascal}', at WORLD pose.
-// Y up, +Z front. Use real sizes in meters. Name every mesh. No lights/cameras/renderers.
-import * as THREE from 'three';
-import {{ RoundedBoxGeometry }} from 'three/addons/geometries/RoundedBoxGeometry.js';
-
-export function build{pascal}(THREE_) {{
- const group = new THREE.Group();
- group.name = '{pascal}';
-
- // ---- PLACEHOLDER (replace with real construction; keep the group name) ----
- // A rounded box filling the planned bbox. Copyable recipes:
- // box: new THREE.BoxGeometry(w, h, d)
- // bevelled: new RoundedBoxGeometry(w, h, d, 4, Math.min(w, h, d) * 0.08)
- // cylinder: new THREE.CylinderGeometry(rTop, rBottom, h, 32)
- // lathe: new THREE.LatheGeometry(points /* Vector2[] (x=radius, y=height) */, 48)
- // extrude w/ bevel:
- // const shape = new THREE.Shape(); shape.moveTo(-w/2, -d/2); shape.lineTo(w/2, -d/2);
- // shape.lineTo(w/2, d/2); shape.lineTo(-w/2, d/2); shape.closePath();
- // const geo = new THREE.ExtrudeGeometry(shape, {{ depth: h, bevelEnabled: true,
- // bevelThickness: 0.004, bevelSize: 0.004, bevelSegments: 3 }});
- // geo.rotateX(-Math.PI / 2); // extrude along +Y instead of +Z
- // merge many: import {{ mergeGeometries }} from 'three/addons/utils/BufferGeometryUtils.js';
- const size = [{ex}, {ey}, {ez}];
- const geometry = new RoundedBoxGeometry(size[0], size[1], size[2], 3, Math.min(...size) * 0.08);
- const material = new THREE.MeshStandardMaterial({{ color: {color}, roughness: 0.6, metalness: 0.05 }});
- const mesh = new THREE.Mesh(geometry, material);
- mesh.name = '{pascal}Body';
- mesh.position.set({cx}, {cy}, {cz}); // world pose (bbox centre)
- group.add(mesh);
- // ---- END PLACEHOLDER ----
-
- return group;
-}}
-"""
-
-PLACEHOLDER_COLORS = ("0x9aa5b1", "0xb08968", "0x7f8c8d", "0xc0a080", "0x6c7a89", "0xa0522d", "0x8fa3ad", "0xbfa27a")
diff --git a/harness/codeverse/languages/urdf/__init__.py b/harness/codeverse/languages/urdf/__init__.py
index 602dbac9..6821abe3 100644
--- a/harness/codeverse/languages/urdf/__init__.py
+++ b/harness/codeverse/languages/urdf/__init__.py
@@ -2,5 +2,823 @@
Modules: ``runtime`` (UrdfBlenderRuntime), ``lint``, ``skeleton``, ``consistency``
(FK ↔ authored geometry), ``wrappers/run_bpy_links.py`` (Blender-side build),
-``wrappers/render_glb_bpy.py`` (fallback renderer). Contract: ``CONTRACT.md``.
+``wrappers/render_glb_bpy.py`` (fallback renderer). Contract: ``CONTRACT.md``."""
+
+from __future__ import annotations
+
+import ast
+import json
+import math
+import os
+import re
+import shutil
+import time
+import xml.etree.ElementTree as ET
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+
+from codeverse.config import Settings, get_settings
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.plan import ArticulatedPlan, JointPlan, PartPlan, Plan
+from codeverse.conventions import to_snake
+from codeverse.languages._ast_lint import describe_parse_failure, safe_parse
+from codeverse.languages._common import ProcResult, read_json_file, run_subprocess
+from codeverse.prompts import PROMPTS_DIR, load_text
+from codeverse.spatial.joints import (
+ UrdfError,
+ load_urdf,
+ pose_samples,
+ sweep_collisions,
+ sweep_findings,
+ urdf_to_glb,
+)
+from codeverse.spatial.joints_model import (
+ JOINT_TYPES,
+ MOVABLE_TYPES,
+ RESERVED_LINK_NAMES,
+ Robot,
+ fk,
+ invert_transform,
+ matrix_to_rpy,
+)
+from codeverse.workspace import ArtifactStage, Workspace
+
+# ===================================================================== consistency
+# (merged from codeverse/languages/urdf/consistency.py, 2026-08-28)
+GATE = "fk_consistency"
+
+
+def _fmt(v: float) -> str:
+ s = f"{v:.6f}".rstrip("0").rstrip(".")
+ return "0" if s in ("", "-0") else s
+
+
+def _vec(v) -> str:
+ return " ".join(_fmt(float(x)) for x in v)
+
+
+def check_fk_consistency(robot: Robot, census_links: dict[str, dict[str, Any]], *, tol_m: float = 0.001) -> list[GateFinding]:
+ """Compare every link's FK-posed mesh bbox at rest with the authored census bbox.
+
+ Returns one ERROR finding per inconsistent link carrying the corrected visual
+ origin (``fix_hint`` is copy-pasteable XML) and an INFO summary otherwise."""
+ T = fk(robot, {})
+ out: list[GateFinding] = []
+ for name, link in robot.links.items():
+ if link.mesh is None:
+ continue
+ row = census_links.get(name)
+ if row is None:
+ out.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=name,
+ message=f"link '{name}' has no authored mesh in census (wrapper exported nothing for it)",
+ fix_hint=f"Create a mesh object named exactly '{name}' in model.py."))
+ continue
+ pts = np.asarray(link.mesh.vertices) @ T[name][:3, :3].T + T[name][:3, 3]
+ fk_min, fk_max = pts.min(axis=0), pts.max(axis=0)
+ au_min, au_max = np.asarray(row["bbox_min"], dtype=float), np.asarray(row["bbox_max"], dtype=float)
+ err = float(max(np.abs(fk_min - au_min).max(), np.abs(fk_max - au_max).max()))
+ if err <= tol_m:
+ continue
+ T_fix = invert_transform(T[name])
+ xyz_fix = T_fix[:3, 3]
+ rpy_fix = matrix_to_rpy(T_fix[:3, :3])
+ cur_xyz = link.visual_origin[:3, 3]
+ cur_rpy = matrix_to_rpy(link.visual_origin[:3, :3])
+ frame_xyz = T[name][:3, 3]
+ out.append(GateFinding(
+ gate=GATE, severity=Severity.ERROR, target=name,
+ message=(f"link '{name}': FK at q=0 puts the mesh at bbox [{_vec(fk_min)}]..[{_vec(fk_max)}] but model.py authored it at "
+ f"[{_vec(au_min)}]..[{_vec(au_max)}] (max error {err*1000:.1f} mm). Its link frame is at world "
+ f"[{_vec(frame_xyz)}] so the visual origin must be the inverse: xyz=\"{_vec(xyz_fix)}\" "
+ f"(you wrote xyz=\"{_vec(cur_xyz)}\" rpy=\"{_vec(cur_rpy)}\")."),
+ fix_hint=(f"In robot.urdf, link '{name}': set BOTH <visual> and <collision> to "
+ f"<origin xyz=\"{_vec(xyz_fix)}\" rpy=\"{_vec(rpy_fix)}\"/> "
+ f"(= -(joint pivot world) when joints have rpy=0; or move the joint origin so the pivot is where you meant)."),
+ data={"error_m": err, "fk_bbox": [fk_min.tolist(), fk_max.tolist()], "authored_bbox": [au_min.tolist(), au_max.tolist()],
+ "corrected_visual_origin": {"xyz": [float(v) for v in xyz_fix], "rpy": [float(v) for v in rpy_fix]},
+ "current_visual_origin": {"xyz": [float(v) for v in cur_xyz], "rpy": [float(v) for v in cur_rpy]},
+ "link_frame_world_xyz": [float(v) for v in frame_xyz]},
+ ))
+ return out
+
+
+# ===================================================================== lint
+# (merged from codeverse/languages/urdf/lint.py, 2026-08-28)
+GATE = "lint:urdf"
+URDF_REL = "src/robot.urdf"
+MODEL_REL = "src/model.py"
+_STATE_WORDS = ("open", "closed", "opened", "extended", "retracted", "raised", "lowered", "folded", "unfolded")
+#: link names double as Blender object names and ``meshes/<link>.glb`` stems: plain
+#: identifiers only (``door``, ``handle_left``, ``DoorHandle``) — never ``Door.001`` / spaces.
+_IDENT = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
+
+#: attribute chains that must not appear in model.py (harness owns these)
+FORBIDDEN_BPY_PREFIXES: tuple[tuple[str, str], ...] = (
+ ("bpy.ops.wm.", "file/session operators (open/save/quit/read_factory_settings) — the harness owns the session"),
+ ("bpy.ops.render.", "rendering — the harness renders"),
+ ("bpy.ops.export_scene.", "exporting — the harness exports meshes/<link>.glb"),
+ ("bpy.ops.export_mesh.", "exporting — the harness exports"),
+ ("bpy.ops.import_scene.", "importing external files — build geometry procedurally"),
+ ("bpy.ops.import_mesh.", "importing external files — build geometry procedurally"),
+)
+FORBIDDEN_MODULES: tuple[str, ...] = ("subprocess", "socket", "urllib", "requests", "http", "shutil", "ctypes", "multiprocessing")
+FORBIDDEN_CALLS: dict[str, str] = {
+ "os.system": "shell access", "os.remove": "file deletion", "os.unlink": "file deletion", "os.rmdir": "file deletion",
+ "sys.exit": "exits Blender before the export — just return/raise instead", "exit": "exits Blender", "quit": "exits Blender",
+ "input": "blocks headless Blender forever",
+}
+WARN_CALLS: dict[str, str] = {
+ "bpy.ops.object.camera_add": "cameras are ignored (and stripped) by the wrapper",
+ "bpy.ops.object.light_add": "lights are ignored (and stripped) by the wrapper",
+ "time.sleep": "pointless in a build script",
+}
+
+
+def _f(sev: Severity, msg: str, *, target: str | None = None, fix: str = "", **data) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=fix, data=data)
+
+
+def _floats(text: str | None) -> list[float] | None:
+ try:
+ return [float(v) for v in (text or "").split()]
+ except ValueError:
+ return None
+
+
+# ------------------------------------------------------------------ URDF
+def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFinding], list[str]]:
+ """Lint URDF source. Returns (findings, link_names)."""
+ out: list[GateFinding] = []
+ try:
+ root = ET.fromstring(text)
+ except ET.ParseError as e:
+ line = getattr(e, "position", (None, None))[0]
+ out.append(_f(Severity.ERROR, f"{label} is not well-formed XML: {e}", target=label,
+ fix="Fix the XML (every <tag> closed, attributes quoted, one <robot> root element).", line=line))
+ return out, []
+ if root.tag != "robot":
+ out.append(_f(Severity.ERROR, f"root element must be <robot>, got <{root.tag}>", target=label,
+ fix='Wrap everything in <robot name="..."> ... </robot>.'))
+ return out, []
+ if not root.get("name"):
+ out.append(_f(Severity.WARN, "<robot> has no name attribute", target=label, fix='<robot name="my_object">'))
+
+ links = root.findall("link")
+ joints = root.findall("joint")
+ link_names: list[str] = []
+ for el in links:
+ name = el.get("name", "")
+ if not name:
+ out.append(_f(Severity.ERROR, "<link> without name", target=label, fix='<link name="base">'))
+ continue
+ if name in link_names:
+ out.append(_f(Severity.ERROR, f"duplicate link name '{name}'", target=name, fix="Link names must be unique."))
+ link_names.append(name)
+ _lint_link(el, name, out)
+ if not link_names:
+ out.append(_f(Severity.ERROR, "URDF has no <link> elements", target=label, fix="Add one <link> per mesh object in model.py."))
+ return out, []
+
+ joint_names: list[str] = []
+ parent_of: dict[str, str] = {}
+ for el in joints:
+ jname = el.get("name", "")
+ if not jname:
+ out.append(_f(Severity.ERROR, "<joint> without name", target=label, fix='<joint name="hinge" type="revolute">'))
+ continue
+ if jname in joint_names:
+ out.append(_f(Severity.ERROR, f"duplicate joint name '{jname}'", target=jname, fix="Joint names must be unique."))
+ joint_names.append(jname)
+ _lint_joint(el, jname, link_names, parent_of, out)
+
+ # tree structure
+ children = set(parent_of)
+ roots = [n for n in link_names if n not in children]
+ if len(roots) != 1:
+ out.append(_f(Severity.ERROR, f"expected exactly one root link (no parent joint), found {roots}", target=label,
+ fix="Every link except the root must be the <child> of exactly one joint; connect extra roots with a fixed joint."))
+ else:
+ for link in link_names:
+ seen, cur = set(), link
+ while cur in parent_of and cur not in seen:
+ seen.add(cur)
+ cur = parent_of[cur]
+ if cur != roots[0]:
+ out.append(_f(Severity.ERROR, f"link '{link}' does not reach the root '{roots[0]}' (cycle or detached)", target=link,
+ fix="Joints must form a single tree rooted at the base link."))
+ return out, link_names
+
+
+def _lint_link(el: ET.Element, name: str, out: list[GateFinding]) -> None:
+ if name in RESERVED_LINK_NAMES:
+ out.append(_f(Severity.ERROR, f"link name '{name}' is reserved by the GLB scene graph (glTF readers use it as the base frame)",
+ target=name, fix="Rename the link (e.g. 'base' or the part's name) in BOTH robot.urdf and model.py."))
+ if not _IDENT.match(name):
+ out.append(_f(Severity.WARN, f"link name '{name}' is not a plain identifier (letters/digits/underscore)", target=name,
+ fix=f"Rename to '{to_snake(name)}' in BOTH robot.urdf and model.py (object names are case-sensitive; "
+ "Blender's auto-suffix '.001' means two objects shared a name)."))
+ if any(w in to_snake(name).split("_") for w in _STATE_WORDS):
+ out.append(_f(Severity.WARN, f"link name '{name}' contains a state word — links are parts, states come from joints", target=name,
+ fix="Name the part (door, drawer, lid), not its state."))
+ visuals = el.findall("visual")
+ expected = f"meshes/{name}.glb"
+ if len(visuals) != 1:
+ out.append(_f(Severity.ERROR, f"link '{name}' has {len(visuals)} <visual> elements; exactly one is required", target=name,
+ fix=f'<visual><origin xyz="..." rpy="0 0 0"/><geometry><mesh filename="{expected}"/></geometry></visual>'))
+ for vis in visuals:
+ geom = vis.find("geometry")
+ mesh = geom.find("mesh") if geom is not None else None
+ if geom is None or mesh is None:
+ kinds = [c.tag for c in geom] if geom is not None else []
+ out.append(_f(Severity.ERROR, f"link '{name}': visual geometry must be a <mesh> (found {kinds or 'nothing'})", target=name,
+ fix=f'Build the shape in model.py and reference <mesh filename="{expected}"/>.'))
+ else:
+ fn = mesh.get("filename", "")
+ if fn != expected:
+ out.append(_f(Severity.ERROR, f"link '{name}': mesh filename '{fn}' must be '{expected}'", target=name,
+ fix=f'<mesh filename="{expected}"/>'))
+ sc = _floats(mesh.get("scale")) if mesh.get("scale") else None
+ if sc is not None and any(abs(s - 1) > 1e-9 for s in sc):
+ out.append(_f(Severity.WARN, f"link '{name}': mesh scale {sc} — model in meters in model.py instead", target=name,
+ fix="Drop the scale attribute and size the geometry in model.py."))
+ _lint_origin(vis.find("origin"), f"link '{name}' visual", name, out)
+ col = el.find("collision")
+ if col is None:
+ out.append(_f(Severity.WARN, f"link '{name}' has no <collision> twin of its visual", target=name,
+ fix="Copy the <visual> block as <collision> (same origin + geometry)."))
+ else:
+ if _sig(col.find("geometry")) != _sig(geom) or _origin_sig(col.find("origin")) != _origin_sig(vis.find("origin")):
+ out.append(_f(Severity.WARN, f"link '{name}': <collision> differs from <visual>; the harness collides the VISUAL mesh", target=name,
+ fix="Make <collision> an identical copy of <visual>."))
+
+
+def _sig(el: ET.Element | None) -> str:
+ return "" if el is None else ET.tostring(el).decode().strip()
+
+
+def _origin_sig(o: ET.Element | None) -> tuple[tuple[float, ...], tuple[float, ...]]:
+ if o is None:
+ return ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0))
+ return (tuple(_floats(o.get("xyz")) or (0.0, 0.0, 0.0)), tuple(_floats(o.get("rpy")) or (0.0, 0.0, 0.0)))
+
+
+def _lint_origin(o: ET.Element | None, what: str, target: str, out: list[GateFinding]) -> None:
+ if o is None:
+ return
+ for attr in ("xyz", "rpy"):
+ if o.get(attr) is None:
+ continue
+ vals = _floats(o.get(attr))
+ if vals is None or len(vals) != 3 or any(not math.isfinite(v) for v in vals):
+ out.append(_f(Severity.ERROR, f"{what}: origin {attr}='{o.get(attr)}' must be 3 finite numbers", target=target,
+ fix=f'<origin {attr}="0 0 0"/>'))
+
+
+def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: dict[str, str], out: list[GateFinding]) -> None:
+ jtype = el.get("type", "")
+ if jtype not in JOINT_TYPES:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': type '{jtype}' must be one of {JOINT_TYPES}", target=jname,
+ fix='type="revolute" (hinge) | "prismatic" (slide) | "continuous" (wheel) | "fixed"'))
+ p = el.find("parent")
+ c = el.find("child")
+ parent = p.get("link", "") if p is not None else ""
+ child = c.get("link", "") if c is not None else ""
+ for role, lk in (("parent", parent), ("child", child)):
+ if not lk:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': missing <{role} link=...>", target=jname, fix=f'<{role} link="base"/>'))
+ elif lk not in link_names:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': {role} link '{lk}' does not exist (links: {link_names})", target=jname,
+ fix="Reference an existing <link name>."))
+ if parent and child and parent == child:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': parent == child", target=jname, fix="A joint connects two different links."))
+ if child:
+ if child in parent_of:
+ out.append(_f(Severity.ERROR, f"link '{child}' is the child of two joints ('{jname}' and another)", target=jname,
+ fix="Each link has exactly one parent joint (tree)."))
+ parent_of[child] = parent
+ _lint_origin(el.find("origin"), f"joint '{jname}'", jname, out)
+ o = el.find("origin")
+ if o is not None and o.get("rpy") and any(abs(v) > 1e-9 for v in (_floats(o.get("rpy")) or [])):
+ out.append(_f(Severity.INFO, f"joint '{jname}' uses a rotated origin (rpy); allowed, but point the <axis> instead where possible", target=jname))
+ ax = el.find("axis")
+ if jtype in MOVABLE_TYPES:
+ if ax is None or ax.get("xyz") is None:
+ out.append(_f(Severity.WARN, f"joint '{jname}': no <axis>; URDF defaults to '1 0 0'", target=jname, fix='<axis xyz="0 0 1"/>'))
+ else:
+ vals = _floats(ax.get("xyz"))
+ if vals is None or len(vals) != 3:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': axis '{ax.get('xyz')}' must be 3 numbers", target=jname, fix='<axis xyz="0 0 1"/>'))
+ else:
+ n = math.sqrt(sum(v * v for v in vals))
+ if n < 1e-9:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': zero axis", target=jname, fix='<axis xyz="0 0 1"/>'))
+ elif abs(n - 1) > 1e-3:
+ unit = " ".join(f"{v / n:.6g}" for v in vals)
+ out.append(_f(Severity.WARN, f"joint '{jname}': axis not unit length (|a|={n:.4g}); auto-normalised", target=jname,
+ fix=f'<axis xyz="{unit}"/>'))
+ lim = el.find("limit")
+ if jtype in ("revolute", "prismatic"):
+ lo = _floats(lim.get("lower")) if lim is not None and lim.get("lower") is not None else None
+ hi = _floats(lim.get("upper")) if lim is not None and lim.get("upper") is not None else None
+ if lim is None or not lo or not hi:
+ unit = "rad" if jtype == "revolute" else "m"
+ out.append(_f(Severity.ERROR, f"joint '{jname}': {jtype} joints need <limit lower upper effort velocity> ({unit})", target=jname,
+ fix='<limit lower="0" upper="1.57" effort="10" velocity="1"/>'))
+ else:
+ if hi[0] < lo[0]:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': upper {hi[0]} < lower {lo[0]}", target=jname,
+ fix="Swap lower/upper; if the motion should go the other way, negate the <axis> instead."))
+ if abs(hi[0] - lo[0]) < 1e-9:
+ out.append(_f(Severity.WARN, f"joint '{jname}': lower == upper (joint cannot move)", target=jname,
+ fix="Give the joint a range, or make it type=fixed."))
+ if jtype == "revolute" and hi[0] - lo[0] > 2 * math.pi + 1e-6:
+ out.append(_f(Severity.WARN, f"joint '{jname}': revolute range > 2π — use type=continuous", target=jname))
+ if lim is not None and (lim.get("effort") is None or lim.get("velocity") is None):
+ out.append(_f(Severity.WARN, f"joint '{jname}': <limit> should carry effort and velocity", target=jname,
+ fix='effort="10" velocity="1"'))
+ elif jtype == "continuous" and lim is not None and (lim.get("lower") is not None or lim.get("upper") is not None):
+ out.append(_f(Severity.WARN, f"joint '{jname}': continuous joints have no lower/upper (ignored)", target=jname,
+ fix='<limit effort="10" velocity="1"/> or use type=revolute'))
+ if el.find("mimic") is not None:
+ out.append(_f(Severity.WARN, f"joint '{jname}': <mimic> is ignored by the harness (sweeps move it independently)", target=jname))
+
+
+# ------------------------------------------------------------------ model.py
+class _Visitor(ast.NodeVisitor):
+ def __init__(self) -> None:
+ self.findings: list[GateFinding] = []
+ self.has_bpy = False
+ self.strings: set[str] = set()
+
+ def _chain(self, node: ast.AST) -> str:
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ top = a.name.split(".")[0]
+ if top == "bpy":
+ self.has_bpy = True
+ if top in FORBIDDEN_MODULES:
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: import of '{a.name}' is not allowed in model.py",
+ target=MODEL_REL, fix="Build geometry with bpy/bmesh/mathutils/math only.", line=node.lineno))
+ self.generic_visit(node)
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ top = (node.module or "").split(".")[0]
+ if top == "bpy":
+ self.has_bpy = True
+ if top in FORBIDDEN_MODULES:
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: import from '{node.module}' is not allowed in model.py",
+ target=MODEL_REL, fix="Build geometry with bpy/bmesh/mathutils/math only.", line=node.lineno))
+ if top == "codeverse":
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: model.py must not import the harness", target=MODEL_REL,
+ fix="Raw bpy only.", line=node.lineno))
+ self.generic_visit(node)
+
+ def visit_Call(self, node: ast.Call) -> None:
+ chain = self._chain(node.func)
+ for prefix, why in FORBIDDEN_BPY_PREFIXES:
+ if chain.startswith(prefix):
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: {chain}() is forbidden: {why}", target=MODEL_REL,
+ fix="Delete this call; the harness owns sessions/exports/renders.", line=node.lineno))
+ if chain in FORBIDDEN_CALLS:
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: {chain}() is forbidden: {FORBIDDEN_CALLS[chain]}",
+ target=MODEL_REL, fix="Remove the call.", line=node.lineno))
+ if chain in WARN_CALLS:
+ self.findings.append(_f(Severity.WARN, f"line {node.lineno}: {chain}(): {WARN_CALLS[chain]}", target=MODEL_REL, line=node.lineno))
+ if chain == "open" and len(node.args) > 1 and isinstance(node.args[1], ast.Constant) and "w" in str(node.args[1].value):
+ self.findings.append(_f(Severity.WARN, f"line {node.lineno}: writing files from model.py is ignored by the harness",
+ target=MODEL_REL, line=node.lineno))
+ self.generic_visit(node)
+
+ def visit_While(self, node: ast.While) -> None:
+ if isinstance(node.test, ast.Constant) and node.test.value is True:
+ self.findings.append(_f(Severity.WARN, f"line {node.lineno}: 'while True' in a build script risks a hang", target=MODEL_REL, line=node.lineno))
+ self.generic_visit(node)
+
+ def visit_Constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, str):
+ self.strings.add(node.value)
+
+
+def lint_model_text(text: str, link_names: list[str], *, label: str = MODEL_REL) -> list[GateFinding]:
+ """AST lint of model.py: forbidden APIs + every URDF link name appears as a string literal."""
+ tree, exc = safe_parse(text, label)
+ if tree is None:
+ msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
+ return [_f(Severity.ERROR, f"{label}:{line or '?'}: {msg}", target=label, fix=hint, line=line)]
+ v = _Visitor()
+ v.visit(tree)
+ out = v.findings
+ if not v.has_bpy:
+ out.append(_f(Severity.ERROR, f"{label} never imports bpy", target=label, fix="import bpy"))
+ for link in link_names:
+ if link not in v.strings and not any(link in s for s in v.strings):
+ out.append(_f(Severity.WARN, f"link '{link}' never appears as a string in {label} — the wrapper looks for an object named exactly '{link}'",
+ target=link, fix=f'obj.name = "{link}"'))
+ return out
+
+
+# ------------------------------------------------------------------ workspace
+def lint_workspace(ws: Workspace) -> GateReport:
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ urdf_p = ws.root / URDF_REL
+ model_p = ws.root / MODEL_REL
+ link_names: list[str] = []
+ if not urdf_p.is_file():
+ findings.append(_f(Severity.ERROR, f"missing {URDF_REL}", target=URDF_REL, fix="Write src/robot.urdf (see the contract)."))
+ else:
+ f, link_names = lint_urdf_text(urdf_p.read_text())
+ findings.extend(f)
+ if not model_p.is_file():
+ findings.append(_f(Severity.ERROR, f"missing {MODEL_REL}", target=MODEL_REL, fix="Write src/model.py (pure bpy, one object per link)."))
+ else:
+ findings.extend(lint_model_text(model_p.read_text(), link_names))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+def lint_files(urdf_path: Path, model_path: Path | None = None) -> GateReport:
+ """Lint arbitrary file paths (CLI / tests)."""
+ t0 = time.time()
+ findings, links = lint_urdf_text(Path(urdf_path).read_text(), label=str(urdf_path))
+ if model_path is not None:
+ findings.extend(lint_model_text(Path(model_path).read_text(), links, label=str(model_path)))
+ return GateReport(gate=GATE, passed=not any(f.severity == Severity.ERROR for f in findings), findings=findings,
+ duration_ms=int((time.time() - t0) * 1000))
+
+
+# ===================================================================== skeleton
+# (merged from codeverse/languages/urdf/skeleton.py, 2026-08-28)
+DEFAULT_EFFORT = 10.0
+DEFAULT_VELOCITY = 1.0
+
+
+@dataclass(frozen=True)
+class LinkFrame:
+ """World placement of one link frame at rest + its plan bbox."""
+
+ name: str
+ frame_xyz: tuple[float, float, float]
+ bbox_center: tuple[float, float, float]
+ bbox_extents: tuple[float, float, float]
+ parent_joint: str | None
+
+
+@dataclass(frozen=True)
+class JointRow:
+ name: str
+ type: str
+ parent: str
+ child: str
+ origin_xyz: tuple[float, float, float]
+ axis: tuple[float, float, float]
+ lower: float | None
+ upper: float | None
+ rest: float = 0.0 # plan rest value the limits were shifted by (0 → limits == plan limits)
+
+
+@dataclass
+class UrdfFrames:
+ robot_name: str
+ root: str
+ links: dict[str, LinkFrame]
+ joints: list[JointRow]
+
+
+def _fmt(v: float) -> str:
+ s = f"{v:.6f}".rstrip("0").rstrip(".")
+ return "0" if s in ("", "-0") else s
+
+
+def _vec(v: tuple[float, float, float]) -> str:
+ return " ".join(_fmt(x) for x in v)
+
+
+def _expand_parts(plan: ArticulatedPlan) -> list[tuple[str, PartPlan, tuple[float, float, float]]]:
+ """(link_name, part, bbox_center) — parts with ``instances > 1`` become ``<name>_1..n``
+ spread along +x so the baseline has no overlaps (the agent repositions them)."""
+ out = []
+ for p in plan.parts:
+ base = to_snake(p.name)
+ if p.instances <= 1:
+ out.append((base, p, tuple(p.bbox.center)))
+ continue
+ cx, cy, cz = p.bbox.center
+ step = p.bbox.extents[0] * 1.5
+ for i in range(p.instances):
+ out.append((f"{base}_{i + 1}", p, (cx + i * step, cy, cz)))
+ return out
+
+
+def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
+ """Pure function: plan → link frames + joint rows in the enforced convention."""
+ parts = _expand_parts(plan)
+ base_names = {to_snake(p.name) for p in plan.parts}
+ instance_links = {n for n, p, _ in parts if p.instances > 1}
+ root = to_snake(plan.root_link)
+ links: dict[str, LinkFrame] = {}
+ pivot_of: dict[str, tuple[float, float, float]] = {}
+ parent_of: dict[str, str] = {}
+ joints: list[JointRow] = []
+
+ offsets = {n: tuple(c - o for c, o in zip(center, p.bbox.center, strict=True)) for n, p, center in parts}
+
+ def add_joint(j: JointPlan, child: str, parent: str, suffix: str = "") -> None:
+ pivot_of[child] = tuple(float(v) + o for v, o in zip(j.pivot, offsets[child], strict=True))
+ parent_of[child] = parent
+ lower = upper = None
+ if j.type in ("revolute", "prismatic"):
+ lower, upper = j.lower - j.rest, j.upper - j.rest
+ joints.append(JointRow(name=to_snake(j.name) + suffix, type=j.type, parent=parent, child=child,
+ origin_xyz=(0.0, 0.0, 0.0), axis=tuple(float(v) for v in j.axis), lower=lower, upper=upper,
+ rest=float(j.rest) if lower is not None else 0.0))
+
+ for j in plan.joints:
+ parent, child = to_snake(j.parent), to_snake(j.child)
+ if parent in base_names and parent not in {n for n, _, _ in parts}:
+ parent = f"{parent}_1" # joint to an instanced parent → first instance
+ children = [n for n, p, _ in parts if n == child or (n in instance_links and n.rsplit("_", 1)[0] == child)]
+ for k, c in enumerate(children):
+ add_joint(j, c, parent, "" if len(children) == 1 else f"_{k + 1}")
+
+ # link frames: root at origin, others at their pivot
+ for name, p, center in parts:
+ frame = (0.0, 0.0, 0.0) if name == root else pivot_of.get(name, (0.0, 0.0, 0.0))
+ pj = next((jr.name for jr in joints if jr.child == name), None)
+ links[name] = LinkFrame(name=name, frame_xyz=frame, bbox_center=center,
+ bbox_extents=tuple(float(v) for v in p.bbox.extents), parent_joint=pj)
+ # joint origins relative to the parent link frame
+ fixed: list[JointRow] = []
+ for jr in joints:
+ pf = links[jr.parent].frame_xyz
+ cf = links[jr.child].frame_xyz
+ fixed.append(JointRow(name=jr.name, type=jr.type, parent=jr.parent, child=jr.child,
+ origin_xyz=tuple(c - p for c, p in zip(cf, pf, strict=True)), axis=jr.axis,
+ lower=jr.lower, upper=jr.upper, rest=jr.rest))
+ return UrdfFrames(robot_name=to_snake(plan.object_name), root=root, links=links, joints=fixed)
+
+
+# ------------------------------------------------------------------ text renderers
+def _limit_note(jr: JointRow) -> str:
+ """Comment explaining a rest-shifted limit (empty when the plan's rest is 0)."""
+ if jr.lower is None or jr.upper is None or abs(jr.rest) < 1e-12:
+ return ""
+ return (f" <!-- plan lower={_fmt(jr.lower + jr.rest)} upper={_fmt(jr.upper + jr.rest)} rest={_fmt(jr.rest)}: "
+ f"the mesh is authored at rest, so q=0 = plan {_fmt(jr.rest)} and the limits are shifted by -rest -->")
+
+
+def render_urdf(frames: UrdfFrames) -> str:
+ lines = ['<?xml version="1.0"?>', f'<robot name="{frames.robot_name}">']
+ lines.append(" <!-- link frames: root at the world origin; every other link frame sits at its joint pivot (world, rest pose). -->")
+ lines.append(" <!-- visual/collision origin = -(link frame world) because meshes/<link>.glb hold WORLD coordinates at rest. -->")
+ lines.append(" <!-- q=0 is the authored pose (the plan's rest pose); limits are the plan's lower-rest .. upper-rest. -->")
+ for name, lf in frames.links.items():
+ vis = tuple(-v for v in lf.frame_xyz)
+ lines.append(f' <link name="{name}"> <!-- frame at world {_vec(lf.frame_xyz)} -->')
+ for tag in ("visual", "collision"):
+ lines.append(f' <{tag}><origin xyz="{_vec(vis)}" rpy="0 0 0"/><geometry><mesh filename="meshes/{name}.glb"/></geometry></{tag}>')
+ lines.append(" </link>")
+ for jr in frames.joints:
+ lines.append(f' <joint name="{jr.name}" type="{jr.type}">')
+ lines.append(f' <parent link="{jr.parent}"/>')
+ lines.append(f' <child link="{jr.child}"/>')
+ lines.append(f' <origin xyz="{_vec(jr.origin_xyz)}" rpy="0 0 0"/> <!-- pivot_world(child) - frame_world(parent) -->')
+ if jr.type != "fixed":
+ lines.append(f' <axis xyz="{_vec(jr.axis)}"/>')
+ lim = f'effort="{_fmt(DEFAULT_EFFORT)}" velocity="{_fmt(DEFAULT_VELOCITY)}"'
+ if jr.lower is not None and jr.upper is not None:
+ lim = f'lower="{_fmt(jr.lower)}" upper="{_fmt(jr.upper)}" ' + lim
+ lines.append(f" <limit {lim}/>" + _limit_note(jr))
+ lines.append(" </joint>")
+ lines.append("</robot>")
+ return "\n".join(lines) + "\n"
+
+
+def render_model_py(plan: ArticulatedPlan, frames: UrdfFrames) -> str:
+ parts_by_link = {n: p for n, p, _ in _expand_parts(plan)}
+ head = f'''"""{plan.object_name} — link meshes for robot.urdf (pure bpy, Z-up, -Y front, meters).
+
+CONTRACT: build ONE mesh object per URDF link, named EXACTLY like the link, placed
+at its REST-POSE WORLD position (= URDF q=0, the pose the plan's bboxes describe).
+Extra helper objects must be parented under a link object (they are joined into
+it). No cameras / lights / render / export calls.
+Replace every placeholder box below with real, detailed geometry; keep the names.
"""
+import bpy
+import bmesh # noqa: F401 (handy for detail)
+import math # noqa: F401
+from mathutils import Vector # noqa: F401
+
+
+def box(name, center, size):
+ """Axis-aligned box helper: center/size in world meters; returns the object."""
+ bpy.ops.mesh.primitive_cube_add(size=1.0, location=center)
+ ob = bpy.context.active_object
+ ob.name = name
+ ob.scale = size
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+ return ob
+
+
+'''
+ body = []
+ for name, lf in frames.links.items():
+ p = parts_by_link[name]
+ role = (p.role or "").replace("\n", " ")
+ desc = (p.description or "").replace("\n", " ")
+ body.append(f"# link '{name}': {role}\n# {desc}")
+ if lf.parent_joint:
+ jr = next(j for j in frames.joints if j.name == lf.parent_joint)
+ note = f" (plan rest={_fmt(jr.rest)} → this pose is URDF q=0)" if abs(jr.rest) > 1e-12 else ""
+ body.append(f"# joint '{lf.parent_joint}' pivot (world) = {lf.frame_xyz}{note}")
+ body.append(f"{name} = box({name!r}, center={tuple(round(v, 4) for v in lf.bbox_center)}, "
+ f"size={tuple(round(v, 4) for v in lf.bbox_extents)})\n")
+ tail = f"\n# Sanity: every link object exists\nfor _n in {list(frames.links)!r}:\n assert _n in bpy.data.objects, _n\n"
+ return head + "\n".join(body) + tail
+
+
+def write_skeleton(ws: Workspace, plan: ArticulatedPlan) -> list[Path]:
+ """Write src/model.py + src/robot.urdf; returns the written paths."""
+ frames = compute_urdf_frames(plan)
+ ws.src.mkdir(parents=True, exist_ok=True)
+ model = ws.src / "model.py"
+ urdf = ws.src / "robot.urdf"
+ model.write_text(render_model_py(plan, frames))
+ urdf.write_text(render_urdf(frames))
+ return [model, urdf]
+
+
+# ===================================================================== runtime
+# (merged from codeverse/languages/urdf/runtime.py, 2026-08-28)
+WRAPPER = Path(__file__).resolve().parent / "wrappers" / "run_bpy_links.py"
+CONTRACT_MD = Path(__file__).resolve().parent / "CONTRACT.md"
+REST_PENETRATION_MAX_M = 0.005
+FK_TOL_M = 0.001
+
+#: every canonical artifact this build owns — staged together so a failed build
+#: can never leave a previous round's output looking current
+STAGED_OUTPUTS = ("build.json", "census.json", "meshes", "robot.urdf", "articulation.json", "object.glb")
+
+
+def _tail(s: str, n: int = 3000) -> str:
+ return s[-n:] if s else ""
+
+
+class UrdfBlenderRuntime:
+ language = Language.URDF_BLENDER
+ entry_globs = (ENTRY_FILE[Language.URDF_BLENDER], "src/robot.urdf")
+
+ # ------------------------------------------------------------ protocol
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ if not isinstance(plan, ArticulatedPlan):
+ raise TypeError(f"urdf_blender skeleton needs an ArticulatedPlan, got {type(plan).__name__}")
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ def contract_doc(self) -> str:
+ try:
+ return load_text("urdf/contract.md")
+ except FileNotFoundError:
+ return CONTRACT_MD.read_text()
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "urdf" / "cookbook.md"
+
+ # ------------------------------------------------------------ build
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ """All six canonical outputs go through one :class:`ArtifactStage`: entering
+ it invalidates them BEFORE any early return can leak a previous round's
+ files, everything is written to staging, and only an ``ok=True`` build
+ promotes the full set. Every exit path publishes the FINAL BuildResult as
+ ``artifacts/build.json`` — the wrapper's own build.json used to stay on disk
+ saying ``ok: true`` while a post-wrapper check (UrdfError / FkInconsistent /
+ RestPenetration) failed the build."""
+ t0 = time.time()
+ settings = get_settings()
+ timeout_s = timeout_s or settings.limits.build_timeout_s
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ with ws.stage_artifacts(*STAGED_OUTPUTS) as stage:
+ return self._build_staged(ws, stage, t0=t0, settings=settings, timeout_s=timeout_s)
+
+ def _build_staged(self, ws: Workspace, stage: ArtifactStage, *, t0: float, settings: Settings,
+ timeout_s: int) -> BuildResult:
+ art = ws.artifacts
+
+ def finish(res: BuildResult) -> BuildResult:
+ # disk never contradicts the returned result: build.json is ALWAYS the
+ # final BuildResult; the rest of the set is published only on ok
+ ws.write_json(stage.path("build.json"), res)
+ if res.ok:
+ stage.promote()
+ elif stage.path("census.json").is_file():
+ stage.promote("build.json", "census.json")
+ else:
+ stage.promote("build.json")
+ return res
+
+ def fail(error_type: str, message: str, *, file: str = "src/robot.urdf", line: int | None = None,
+ census: dict[str, Any] | None = None, **kw: Any) -> BuildResult:
+ return finish(BuildResult(ok=False, language=self.language.value, error_type=error_type,
+ error_message=message, error_file=file, error_line=line,
+ duration_ms=int((time.time() - t0) * 1000), census=census or {}, **kw))
+
+ # 1. lint (cheap, no Blender)
+ lint = self.lint(ws)
+ census: dict[str, Any] = {"lint": [f.model_dump(mode="json") for f in lint.findings]}
+ if not lint.passed:
+ errs = lint.errors
+ msg = "\n".join(f"- {f.message}" + (f" → {f.fix_hint}" if f.fix_hint else "") for f in errs[:12])
+ return fail("LintError", f"{len(errs)} lint error(s):\n{msg}", file=str(errs[0].target or "src/robot.urdf"),
+ line=errs[0].data.get("line"), census=census)
+
+ # 2. Blender wrapper (writes build.json / census.json / meshes/ into the staging dir)
+ blender = settings.resolve_blender()
+ if not blender:
+ return fail("BlenderNotFound", "no Blender binary (set CV3D_BINARIES__BLENDER)", file="", census=census)
+ build_json, census_json = stage.path("build.json"), stage.path("census.json")
+ proc = _run_blender(blender, ws, stage.staging_dir, timeout_s, settings.limits.bpy_rlimit_gb)
+ if proc.timed_out:
+ return fail("Timeout", f"Blender build exceeded {timeout_s}s (killed)", file="src/model.py", census=census,
+ stdout_tail=_tail(proc.stdout), stderr_tail=_tail(proc.stderr))
+ if not build_json.is_file():
+ return fail("WrapperCrash", f"wrapper produced no build.json (exit {proc.returncode})", file="src/model.py",
+ census=census, stdout_tail=_tail(proc.stdout), stderr_tail=_tail(proc.stderr))
+ wb = read_json_file(build_json)
+ wcensus = read_json_file(census_json) if census_json.is_file() else {}
+ census.update({k: wcensus.get(k) for k in ("objects", "links", "unmatched_objects", "missing_links", "hints") if k in wcensus})
+ if not wb.get("ok"):
+ hints = "\n".join(f" hint: {h}" for h in (wcensus.get("hints") or {}).values())
+ return fail(wb.get("error_type") or "ScriptError", (wb.get("error_message") or "") + ("\n" + hints if hints else ""),
+ file=wb.get("error_file") or "src/model.py", line=wb.get("error_line"), census=census,
+ stdout_tail=_tail(wb.get("stdout_tail", "") or proc.stdout),
+ stderr_tail=_tail(wb.get("stderr_tail", "") or proc.stderr))
+
+ # 3. URDF copy + load (staged files; extra_paths name the canonical homes)
+ urdf_staged = stage.path("robot.urdf")
+ shutil.copyfile(ws.root / "src" / "robot.urdf", urdf_staged)
+ extra = {"urdf": str(art / "robot.urdf"), "meshes_dir": str(art / "meshes")}
+ try:
+ robot = load_urdf(urdf_staged, stage.path("meshes"))
+ except UrdfError as e:
+ return fail("UrdfError", str(e), census=census)
+
+ # 4. FK consistency
+ fk_findings = check_fk_consistency(robot, census.get("links") or {}, tol_m=FK_TOL_M)
+ census["fk_check"] = [f.model_dump(mode="json") for f in fk_findings]
+ if fk_findings:
+ msg = "\n".join(f"- {f.as_line()}" for f in fk_findings)
+ return fail("FkInconsistent", f"URDF frames do not reproduce the authored geometry:\n{msg}", census=census)
+
+ # 5. pose sweep
+ report = sweep_collisions(robot, pose_samples(robot, n_random=8, seed=0))
+ findings = sweep_findings(report, rest_max_m=REST_PENETRATION_MAX_M)
+ stage.path("articulation.json").write_text(json.dumps({"report": report.model_dump(mode="json"),
+ "findings": [f.model_dump(mode="json") for f in findings]}, indent=1))
+ extra["articulation"] = str(art / "articulation.json")
+ for name, n in report.summary.link_islands.items():
+ census.setdefault("links", {}).setdefault(name, {})["islands"] = n
+ census["articulation"] = {"summary": report.summary.model_dump(mode="json"),
+ "findings": [f.model_dump(mode="json") for f in findings],
+ "n_joints": len(robot.joints), "movable_joints": [j.name for j in robot.movable_joints()]}
+
+ # 6. canonical GLB at rest
+ urdf_to_glb(robot, stage.path("object.glb"), None)
+ extra["object_glb"] = str(art / "object.glb")
+ res = BuildResult(ok=True, language=self.language.value, glb_path=str(art / "object.glb"), extra_paths=extra,
+ stdout_tail=_tail(wb.get("stdout_tail", "")), duration_ms=int((time.time() - t0) * 1000), census=census)
+ if report.summary.rest_max_penetration_m > REST_PENETRATION_MAX_M:
+ worst = [f for f in findings if f.data.get("pose") == {} and f.severity == "error"]
+ res.ok = False
+ res.error_type = "RestPenetration"
+ res.error_file = "src/model.py"
+ res.error_message = (f"links interpenetrate by {report.summary.rest_max_penetration_m*1000:.1f} mm at the rest pose "
+ f"(max {REST_PENETRATION_MAX_M*1000:.0f} mm):\n" +
+ "\n".join(f"- {f.as_line()}" for f in worst[:8]))
+ res.glb_path = None # the fresh GLB is NOT published on a failed build
+ res.extra_paths = {}
+ return finish(res)
+
+
+def _run_blender(blender: str, ws: Workspace, art: Path, timeout_s: int, rlimit_gb: int) -> ProcResult:
+ cmd = [blender, "-b", "--factory-startup", "--python", str(WRAPPER), "--",
+ "--script", str(ws.root / "src" / "model.py"), "--urdf", str(ws.root / "src" / "robot.urdf"),
+ "--out", str(art), "--rlimit-gb", str(rlimit_gb)]
+ # whitelist env (no inherited PYTHONPATH, user config pinned into artifacts) — deliberately
+ # stricter than blender.runtime.blender_env(); keep it that way
+ env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": os.environ.get("HOME", str(ws.root)),
+ "PYTHONDONTWRITEBYTECODE": "1", "PYTHONNOUSERSITE": "1", "BLENDER_USER_CONFIG": str(art / ".blender_config")}
+ return run_subprocess(cmd, cwd=ws.root, env=env, timeout_s=timeout_s)
diff --git a/harness/codeverse/languages/urdf/consistency.py b/harness/codeverse/languages/urdf/consistency.py
deleted file mode 100644
index a2d6e9f6..00000000
--- a/harness/codeverse/languages/urdf/consistency.py
+++ /dev/null
@@ -1,78 +0,0 @@
-"""FK ↔ authored-geometry consistency check for ``urdf_blender`` builds.
-
-``model.py`` authors every link mesh at its rest-pose WORLD placement; the
-wrapper exports those world coordinates into ``meshes/<link>.glb`` and records
-the world bbox per link in ``census.json``. The URDF must then place each mesh
-back exactly where it was authored at ``q = 0``:
-
- T_link_rest(q=0) · T_visual · mesh_world == mesh_world
- ⇒ T_visual == inv(T_link_rest)
-
-We verify this numerically (bbox of the FK-posed mesh vs the census bbox, 1 mm)
-and report the exact corrected ``<origin>`` when it is wrong.
-"""
-
-from __future__ import annotations
-
-from typing import Any
-
-import numpy as np
-
-from codeverse.contracts.artifacts import GateFinding, Severity
-from codeverse.spatial.joints_model import Robot, fk, invert_transform, matrix_to_rpy
-
-GATE = "fk_consistency"
-
-
-def _fmt(v: float) -> str:
- s = f"{v:.6f}".rstrip("0").rstrip(".")
- return "0" if s in ("", "-0") else s
-
-
-def _vec(v) -> str:
- return " ".join(_fmt(float(x)) for x in v)
-
-
-def check_fk_consistency(robot: Robot, census_links: dict[str, dict[str, Any]], *, tol_m: float = 0.001) -> list[GateFinding]:
- """Compare every link's FK-posed mesh bbox at rest with the authored census bbox.
-
- Returns one ERROR finding per inconsistent link carrying the corrected visual
- origin (``fix_hint`` is copy-pasteable XML) and an INFO summary otherwise."""
- T = fk(robot, {})
- out: list[GateFinding] = []
- for name, link in robot.links.items():
- if link.mesh is None:
- continue
- row = census_links.get(name)
- if row is None:
- out.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=name,
- message=f"link '{name}' has no authored mesh in census (wrapper exported nothing for it)",
- fix_hint=f"Create a mesh object named exactly '{name}' in model.py."))
- continue
- pts = np.asarray(link.mesh.vertices) @ T[name][:3, :3].T + T[name][:3, 3]
- fk_min, fk_max = pts.min(axis=0), pts.max(axis=0)
- au_min, au_max = np.asarray(row["bbox_min"], dtype=float), np.asarray(row["bbox_max"], dtype=float)
- err = float(max(np.abs(fk_min - au_min).max(), np.abs(fk_max - au_max).max()))
- if err <= tol_m:
- continue
- T_fix = invert_transform(T[name])
- xyz_fix = T_fix[:3, 3]
- rpy_fix = matrix_to_rpy(T_fix[:3, :3])
- cur_xyz = link.visual_origin[:3, 3]
- cur_rpy = matrix_to_rpy(link.visual_origin[:3, :3])
- frame_xyz = T[name][:3, 3]
- out.append(GateFinding(
- gate=GATE, severity=Severity.ERROR, target=name,
- message=(f"link '{name}': FK at q=0 puts the mesh at bbox [{_vec(fk_min)}]..[{_vec(fk_max)}] but model.py authored it at "
- f"[{_vec(au_min)}]..[{_vec(au_max)}] (max error {err*1000:.1f} mm). Its link frame is at world "
- f"[{_vec(frame_xyz)}] so the visual origin must be the inverse: xyz=\"{_vec(xyz_fix)}\" "
- f"(you wrote xyz=\"{_vec(cur_xyz)}\" rpy=\"{_vec(cur_rpy)}\")."),
- fix_hint=(f"In robot.urdf, link '{name}': set BOTH <visual> and <collision> to "
- f"<origin xyz=\"{_vec(xyz_fix)}\" rpy=\"{_vec(rpy_fix)}\"/> "
- f"(= -(joint pivot world) when joints have rpy=0; or move the joint origin so the pivot is where you meant)."),
- data={"error_m": err, "fk_bbox": [fk_min.tolist(), fk_max.tolist()], "authored_bbox": [au_min.tolist(), au_max.tolist()],
- "corrected_visual_origin": {"xyz": [float(v) for v in xyz_fix], "rpy": [float(v) for v in rpy_fix]},
- "current_visual_origin": {"xyz": [float(v) for v in cur_xyz], "rpy": [float(v) for v in cur_rpy]},
- "link_frame_world_xyz": [float(v) for v in frame_xyz]},
- ))
- return out
diff --git a/harness/codeverse/languages/urdf/lint.py b/harness/codeverse/languages/urdf/lint.py
deleted file mode 100644
index b71717cb..00000000
--- a/harness/codeverse/languages/urdf/lint.py
+++ /dev/null
@@ -1,371 +0,0 @@
-"""Static lint for the ``urdf_blender`` language: ``src/robot.urdf`` (URDF rules)
-and ``src/model.py`` (bpy pitfalls + link-name coverage). Gate ``lint:urdf``.
-
-Every finding carries a copyable ``fix_hint``. Errors block the build; warnings
-are shown to the agent/judge.
-"""
-
-from __future__ import annotations
-
-import ast
-import math
-import re
-import time
-import xml.etree.ElementTree as ET
-from pathlib import Path
-
-from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
-from codeverse.conventions import to_snake
-from codeverse.languages._ast_lint import describe_parse_failure, safe_parse
-from codeverse.spatial.joints_model import JOINT_TYPES, MOVABLE_TYPES, RESERVED_LINK_NAMES
-from codeverse.workspace import Workspace
-
-GATE = "lint:urdf"
-URDF_REL = "src/robot.urdf"
-MODEL_REL = "src/model.py"
-_STATE_WORDS = ("open", "closed", "opened", "extended", "retracted", "raised", "lowered", "folded", "unfolded")
-#: link names double as Blender object names and ``meshes/<link>.glb`` stems: plain
-#: identifiers only (``door``, ``handle_left``, ``DoorHandle``) — never ``Door.001`` / spaces.
-_IDENT = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
-
-#: attribute chains that must not appear in model.py (harness owns these)
-FORBIDDEN_BPY_PREFIXES: tuple[tuple[str, str], ...] = (
- ("bpy.ops.wm.", "file/session operators (open/save/quit/read_factory_settings) — the harness owns the session"),
- ("bpy.ops.render.", "rendering — the harness renders"),
- ("bpy.ops.export_scene.", "exporting — the harness exports meshes/<link>.glb"),
- ("bpy.ops.export_mesh.", "exporting — the harness exports"),
- ("bpy.ops.import_scene.", "importing external files — build geometry procedurally"),
- ("bpy.ops.import_mesh.", "importing external files — build geometry procedurally"),
-)
-FORBIDDEN_MODULES: tuple[str, ...] = ("subprocess", "socket", "urllib", "requests", "http", "shutil", "ctypes", "multiprocessing")
-FORBIDDEN_CALLS: dict[str, str] = {
- "os.system": "shell access", "os.remove": "file deletion", "os.unlink": "file deletion", "os.rmdir": "file deletion",
- "sys.exit": "exits Blender before the export — just return/raise instead", "exit": "exits Blender", "quit": "exits Blender",
- "input": "blocks headless Blender forever",
-}
-WARN_CALLS: dict[str, str] = {
- "bpy.ops.object.camera_add": "cameras are ignored (and stripped) by the wrapper",
- "bpy.ops.object.light_add": "lights are ignored (and stripped) by the wrapper",
- "time.sleep": "pointless in a build script",
-}
-
-
-def _f(sev: Severity, msg: str, *, target: str | None = None, fix: str = "", **data) -> GateFinding:
- return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=fix, data=data)
-
-
-def _floats(text: str | None) -> list[float] | None:
- try:
- return [float(v) for v in (text or "").split()]
- except ValueError:
- return None
-
-
-# ------------------------------------------------------------------ URDF
-def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFinding], list[str]]:
- """Lint URDF source. Returns (findings, link_names)."""
- out: list[GateFinding] = []
- try:
- root = ET.fromstring(text)
- except ET.ParseError as e:
- line = getattr(e, "position", (None, None))[0]
- out.append(_f(Severity.ERROR, f"{label} is not well-formed XML: {e}", target=label,
- fix="Fix the XML (every <tag> closed, attributes quoted, one <robot> root element).", line=line))
- return out, []
- if root.tag != "robot":
- out.append(_f(Severity.ERROR, f"root element must be <robot>, got <{root.tag}>", target=label,
- fix='Wrap everything in <robot name="..."> ... </robot>.'))
- return out, []
- if not root.get("name"):
- out.append(_f(Severity.WARN, "<robot> has no name attribute", target=label, fix='<robot name="my_object">'))
-
- links = root.findall("link")
- joints = root.findall("joint")
- link_names: list[str] = []
- for el in links:
- name = el.get("name", "")
- if not name:
- out.append(_f(Severity.ERROR, "<link> without name", target=label, fix='<link name="base">'))
- continue
- if name in link_names:
- out.append(_f(Severity.ERROR, f"duplicate link name '{name}'", target=name, fix="Link names must be unique."))
- link_names.append(name)
- _lint_link(el, name, out)
- if not link_names:
- out.append(_f(Severity.ERROR, "URDF has no <link> elements", target=label, fix="Add one <link> per mesh object in model.py."))
- return out, []
-
- joint_names: list[str] = []
- parent_of: dict[str, str] = {}
- for el in joints:
- jname = el.get("name", "")
- if not jname:
- out.append(_f(Severity.ERROR, "<joint> without name", target=label, fix='<joint name="hinge" type="revolute">'))
- continue
- if jname in joint_names:
- out.append(_f(Severity.ERROR, f"duplicate joint name '{jname}'", target=jname, fix="Joint names must be unique."))
- joint_names.append(jname)
- _lint_joint(el, jname, link_names, parent_of, out)
-
- # tree structure
- children = set(parent_of)
- roots = [n for n in link_names if n not in children]
- if len(roots) != 1:
- out.append(_f(Severity.ERROR, f"expected exactly one root link (no parent joint), found {roots}", target=label,
- fix="Every link except the root must be the <child> of exactly one joint; connect extra roots with a fixed joint."))
- else:
- for link in link_names:
- seen, cur = set(), link
- while cur in parent_of and cur not in seen:
- seen.add(cur)
- cur = parent_of[cur]
- if cur != roots[0]:
- out.append(_f(Severity.ERROR, f"link '{link}' does not reach the root '{roots[0]}' (cycle or detached)", target=link,
- fix="Joints must form a single tree rooted at the base link."))
- return out, link_names
-
-
-def _lint_link(el: ET.Element, name: str, out: list[GateFinding]) -> None:
- if name in RESERVED_LINK_NAMES:
- out.append(_f(Severity.ERROR, f"link name '{name}' is reserved by the GLB scene graph (glTF readers use it as the base frame)",
- target=name, fix="Rename the link (e.g. 'base' or the part's name) in BOTH robot.urdf and model.py."))
- if not _IDENT.match(name):
- out.append(_f(Severity.WARN, f"link name '{name}' is not a plain identifier (letters/digits/underscore)", target=name,
- fix=f"Rename to '{to_snake(name)}' in BOTH robot.urdf and model.py (object names are case-sensitive; "
- "Blender's auto-suffix '.001' means two objects shared a name)."))
- if any(w in to_snake(name).split("_") for w in _STATE_WORDS):
- out.append(_f(Severity.WARN, f"link name '{name}' contains a state word — links are parts, states come from joints", target=name,
- fix="Name the part (door, drawer, lid), not its state."))
- visuals = el.findall("visual")
- expected = f"meshes/{name}.glb"
- if len(visuals) != 1:
- out.append(_f(Severity.ERROR, f"link '{name}' has {len(visuals)} <visual> elements; exactly one is required", target=name,
- fix=f'<visual><origin xyz="..." rpy="0 0 0"/><geometry><mesh filename="{expected}"/></geometry></visual>'))
- for vis in visuals:
- geom = vis.find("geometry")
- mesh = geom.find("mesh") if geom is not None else None
- if geom is None or mesh is None:
- kinds = [c.tag for c in geom] if geom is not None else []
- out.append(_f(Severity.ERROR, f"link '{name}': visual geometry must be a <mesh> (found {kinds or 'nothing'})", target=name,
- fix=f'Build the shape in model.py and reference <mesh filename="{expected}"/>.'))
- else:
- fn = mesh.get("filename", "")
- if fn != expected:
- out.append(_f(Severity.ERROR, f"link '{name}': mesh filename '{fn}' must be '{expected}'", target=name,
- fix=f'<mesh filename="{expected}"/>'))
- sc = _floats(mesh.get("scale")) if mesh.get("scale") else None
- if sc is not None and any(abs(s - 1) > 1e-9 for s in sc):
- out.append(_f(Severity.WARN, f"link '{name}': mesh scale {sc} — model in meters in model.py instead", target=name,
- fix="Drop the scale attribute and size the geometry in model.py."))
- _lint_origin(vis.find("origin"), f"link '{name}' visual", name, out)
- col = el.find("collision")
- if col is None:
- out.append(_f(Severity.WARN, f"link '{name}' has no <collision> twin of its visual", target=name,
- fix="Copy the <visual> block as <collision> (same origin + geometry)."))
- else:
- if _sig(col.find("geometry")) != _sig(geom) or _origin_sig(col.find("origin")) != _origin_sig(vis.find("origin")):
- out.append(_f(Severity.WARN, f"link '{name}': <collision> differs from <visual>; the harness collides the VISUAL mesh", target=name,
- fix="Make <collision> an identical copy of <visual>."))
-
-
-def _sig(el: ET.Element | None) -> str:
- return "" if el is None else ET.tostring(el).decode().strip()
-
-
-def _origin_sig(o: ET.Element | None) -> tuple[tuple[float, ...], tuple[float, ...]]:
- if o is None:
- return ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0))
- return (tuple(_floats(o.get("xyz")) or (0.0, 0.0, 0.0)), tuple(_floats(o.get("rpy")) or (0.0, 0.0, 0.0)))
-
-
-def _lint_origin(o: ET.Element | None, what: str, target: str, out: list[GateFinding]) -> None:
- if o is None:
- return
- for attr in ("xyz", "rpy"):
- if o.get(attr) is None:
- continue
- vals = _floats(o.get(attr))
- if vals is None or len(vals) != 3 or any(not math.isfinite(v) for v in vals):
- out.append(_f(Severity.ERROR, f"{what}: origin {attr}='{o.get(attr)}' must be 3 finite numbers", target=target,
- fix=f'<origin {attr}="0 0 0"/>'))
-
-
-def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: dict[str, str], out: list[GateFinding]) -> None:
- jtype = el.get("type", "")
- if jtype not in JOINT_TYPES:
- out.append(_f(Severity.ERROR, f"joint '{jname}': type '{jtype}' must be one of {JOINT_TYPES}", target=jname,
- fix='type="revolute" (hinge) | "prismatic" (slide) | "continuous" (wheel) | "fixed"'))
- p = el.find("parent")
- c = el.find("child")
- parent = p.get("link", "") if p is not None else ""
- child = c.get("link", "") if c is not None else ""
- for role, lk in (("parent", parent), ("child", child)):
- if not lk:
- out.append(_f(Severity.ERROR, f"joint '{jname}': missing <{role} link=...>", target=jname, fix=f'<{role} link="base"/>'))
- elif lk not in link_names:
- out.append(_f(Severity.ERROR, f"joint '{jname}': {role} link '{lk}' does not exist (links: {link_names})", target=jname,
- fix="Reference an existing <link name>."))
- if parent and child and parent == child:
- out.append(_f(Severity.ERROR, f"joint '{jname}': parent == child", target=jname, fix="A joint connects two different links."))
- if child:
- if child in parent_of:
- out.append(_f(Severity.ERROR, f"link '{child}' is the child of two joints ('{jname}' and another)", target=jname,
- fix="Each link has exactly one parent joint (tree)."))
- parent_of[child] = parent
- _lint_origin(el.find("origin"), f"joint '{jname}'", jname, out)
- o = el.find("origin")
- if o is not None and o.get("rpy") and any(abs(v) > 1e-9 for v in (_floats(o.get("rpy")) or [])):
- out.append(_f(Severity.INFO, f"joint '{jname}' uses a rotated origin (rpy); allowed, but point the <axis> instead where possible", target=jname))
- ax = el.find("axis")
- if jtype in MOVABLE_TYPES:
- if ax is None or ax.get("xyz") is None:
- out.append(_f(Severity.WARN, f"joint '{jname}': no <axis>; URDF defaults to '1 0 0'", target=jname, fix='<axis xyz="0 0 1"/>'))
- else:
- vals = _floats(ax.get("xyz"))
- if vals is None or len(vals) != 3:
- out.append(_f(Severity.ERROR, f"joint '{jname}': axis '{ax.get('xyz')}' must be 3 numbers", target=jname, fix='<axis xyz="0 0 1"/>'))
- else:
- n = math.sqrt(sum(v * v for v in vals))
- if n < 1e-9:
- out.append(_f(Severity.ERROR, f"joint '{jname}': zero axis", target=jname, fix='<axis xyz="0 0 1"/>'))
- elif abs(n - 1) > 1e-3:
- unit = " ".join(f"{v / n:.6g}" for v in vals)
- out.append(_f(Severity.WARN, f"joint '{jname}': axis not unit length (|a|={n:.4g}); auto-normalised", target=jname,
- fix=f'<axis xyz="{unit}"/>'))
- lim = el.find("limit")
- if jtype in ("revolute", "prismatic"):
- lo = _floats(lim.get("lower")) if lim is not None and lim.get("lower") is not None else None
- hi = _floats(lim.get("upper")) if lim is not None and lim.get("upper") is not None else None
- if lim is None or not lo or not hi:
- unit = "rad" if jtype == "revolute" else "m"
- out.append(_f(Severity.ERROR, f"joint '{jname}': {jtype} joints need <limit lower upper effort velocity> ({unit})", target=jname,
- fix='<limit lower="0" upper="1.57" effort="10" velocity="1"/>'))
- else:
- if hi[0] < lo[0]:
- out.append(_f(Severity.ERROR, f"joint '{jname}': upper {hi[0]} < lower {lo[0]}", target=jname,
- fix="Swap lower/upper; if the motion should go the other way, negate the <axis> instead."))
- if abs(hi[0] - lo[0]) < 1e-9:
- out.append(_f(Severity.WARN, f"joint '{jname}': lower == upper (joint cannot move)", target=jname,
- fix="Give the joint a range, or make it type=fixed."))
- if jtype == "revolute" and hi[0] - lo[0] > 2 * math.pi + 1e-6:
- out.append(_f(Severity.WARN, f"joint '{jname}': revolute range > 2π — use type=continuous", target=jname))
- if lim is not None and (lim.get("effort") is None or lim.get("velocity") is None):
- out.append(_f(Severity.WARN, f"joint '{jname}': <limit> should carry effort and velocity", target=jname,
- fix='effort="10" velocity="1"'))
- elif jtype == "continuous" and lim is not None and (lim.get("lower") is not None or lim.get("upper") is not None):
- out.append(_f(Severity.WARN, f"joint '{jname}': continuous joints have no lower/upper (ignored)", target=jname,
- fix='<limit effort="10" velocity="1"/> or use type=revolute'))
- if el.find("mimic") is not None:
- out.append(_f(Severity.WARN, f"joint '{jname}': <mimic> is ignored by the harness (sweeps move it independently)", target=jname))
-
-
-# ------------------------------------------------------------------ model.py
-class _Visitor(ast.NodeVisitor):
- def __init__(self) -> None:
- self.findings: list[GateFinding] = []
- self.has_bpy = False
- self.strings: set[str] = set()
-
- def _chain(self, node: ast.AST) -> str:
- parts: list[str] = []
- while isinstance(node, ast.Attribute):
- parts.append(node.attr)
- node = node.value
- if isinstance(node, ast.Name):
- parts.append(node.id)
- return ".".join(reversed(parts))
-
- def visit_Import(self, node: ast.Import) -> None:
- for a in node.names:
- top = a.name.split(".")[0]
- if top == "bpy":
- self.has_bpy = True
- if top in FORBIDDEN_MODULES:
- self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: import of '{a.name}' is not allowed in model.py",
- target=MODEL_REL, fix="Build geometry with bpy/bmesh/mathutils/math only.", line=node.lineno))
- self.generic_visit(node)
-
- def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
- top = (node.module or "").split(".")[0]
- if top == "bpy":
- self.has_bpy = True
- if top in FORBIDDEN_MODULES:
- self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: import from '{node.module}' is not allowed in model.py",
- target=MODEL_REL, fix="Build geometry with bpy/bmesh/mathutils/math only.", line=node.lineno))
- if top == "codeverse":
- self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: model.py must not import the harness", target=MODEL_REL,
- fix="Raw bpy only.", line=node.lineno))
- self.generic_visit(node)
-
- def visit_Call(self, node: ast.Call) -> None:
- chain = self._chain(node.func)
- for prefix, why in FORBIDDEN_BPY_PREFIXES:
- if chain.startswith(prefix):
- self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: {chain}() is forbidden: {why}", target=MODEL_REL,
- fix="Delete this call; the harness owns sessions/exports/renders.", line=node.lineno))
- if chain in FORBIDDEN_CALLS:
- self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: {chain}() is forbidden: {FORBIDDEN_CALLS[chain]}",
- target=MODEL_REL, fix="Remove the call.", line=node.lineno))
- if chain in WARN_CALLS:
- self.findings.append(_f(Severity.WARN, f"line {node.lineno}: {chain}(): {WARN_CALLS[chain]}", target=MODEL_REL, line=node.lineno))
- if chain == "open" and len(node.args) > 1 and isinstance(node.args[1], ast.Constant) and "w" in str(node.args[1].value):
- self.findings.append(_f(Severity.WARN, f"line {node.lineno}: writing files from model.py is ignored by the harness",
- target=MODEL_REL, line=node.lineno))
- self.generic_visit(node)
-
- def visit_While(self, node: ast.While) -> None:
- if isinstance(node.test, ast.Constant) and node.test.value is True:
- self.findings.append(_f(Severity.WARN, f"line {node.lineno}: 'while True' in a build script risks a hang", target=MODEL_REL, line=node.lineno))
- self.generic_visit(node)
-
- def visit_Constant(self, node: ast.Constant) -> None:
- if isinstance(node.value, str):
- self.strings.add(node.value)
-
-
-def lint_model_text(text: str, link_names: list[str], *, label: str = MODEL_REL) -> list[GateFinding]:
- """AST lint of model.py: forbidden APIs + every URDF link name appears as a string literal."""
- tree, exc = safe_parse(text, label)
- if tree is None:
- msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
- return [_f(Severity.ERROR, f"{label}:{line or '?'}: {msg}", target=label, fix=hint, line=line)]
- v = _Visitor()
- v.visit(tree)
- out = v.findings
- if not v.has_bpy:
- out.append(_f(Severity.ERROR, f"{label} never imports bpy", target=label, fix="import bpy"))
- for link in link_names:
- if link not in v.strings and not any(link in s for s in v.strings):
- out.append(_f(Severity.WARN, f"link '{link}' never appears as a string in {label} — the wrapper looks for an object named exactly '{link}'",
- target=link, fix=f'obj.name = "{link}"'))
- return out
-
-
-# ------------------------------------------------------------------ workspace
-def lint_workspace(ws: Workspace) -> GateReport:
- t0 = time.time()
- findings: list[GateFinding] = []
- urdf_p = ws.root / URDF_REL
- model_p = ws.root / MODEL_REL
- link_names: list[str] = []
- if not urdf_p.is_file():
- findings.append(_f(Severity.ERROR, f"missing {URDF_REL}", target=URDF_REL, fix="Write src/robot.urdf (see the contract)."))
- else:
- f, link_names = lint_urdf_text(urdf_p.read_text())
- findings.extend(f)
- if not model_p.is_file():
- findings.append(_f(Severity.ERROR, f"missing {MODEL_REL}", target=MODEL_REL, fix="Write src/model.py (pure bpy, one object per link)."))
- else:
- findings.extend(lint_model_text(model_p.read_text(), link_names))
- passed = not any(f.severity == Severity.ERROR for f in findings)
- return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
-
-
-def lint_files(urdf_path: Path, model_path: Path | None = None) -> GateReport:
- """Lint arbitrary file paths (CLI / tests)."""
- t0 = time.time()
- findings, links = lint_urdf_text(Path(urdf_path).read_text(), label=str(urdf_path))
- if model_path is not None:
- findings.extend(lint_model_text(Path(model_path).read_text(), links, label=str(model_path)))
- return GateReport(gate=GATE, passed=not any(f.severity == Severity.ERROR for f in findings), findings=findings,
- duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/languages/urdf/runtime.py b/harness/codeverse/languages/urdf/runtime.py
deleted file mode 100644
index 9694382c..00000000
--- a/harness/codeverse/languages/urdf/runtime.py
+++ /dev/null
@@ -1,202 +0,0 @@
-"""``urdf_blender`` LanguageRuntime: bpy link meshes + hand-written URDF.
-
-build(ws):
- lint URDF/model.py → Blender wrapper (exec model.py, export meshes/<link>.glb,
- census) → load_urdf → FK consistency (authored bbox == FK bbox at q=0) →
- pose sweep (overlaps / floating) → artifacts/object.glb (hierarchical, Y-up)
- + artifacts/robot.urdf + artifacts/meshes/ + artifacts/articulation.json.
-
-``ok`` iff the script ran, the URDF is valid, FK is consistent and nothing
-interpenetrates by more than ``REST_PENETRATION_MAX_M`` at rest. Overlaps in
-moved poses and floating links are reported in ``census["articulation"]`` for
-the gate layer (``sweep_findings``).
-"""
-
-from __future__ import annotations
-
-import json
-import os
-import shutil
-import time
-from pathlib import Path
-from typing import Any
-
-from codeverse.config import Settings, get_settings
-from codeverse.contracts.artifacts import BuildResult, GateReport
-from codeverse.contracts.common import ENTRY_FILE, Language
-from codeverse.contracts.plan import ArticulatedPlan, Plan
-from codeverse.languages._common import ProcResult, read_json_file, run_subprocess
-from codeverse.languages.urdf.consistency import check_fk_consistency
-from codeverse.languages.urdf.lint import lint_workspace
-from codeverse.languages.urdf.skeleton import write_skeleton
-from codeverse.prompts import PROMPTS_DIR, load_text
-from codeverse.spatial.joints import (
- UrdfError,
- load_urdf,
- pose_samples,
- sweep_collisions,
- sweep_findings,
- urdf_to_glb,
-)
-from codeverse.workspace import ArtifactStage, Workspace
-
-WRAPPER = Path(__file__).resolve().parent / "wrappers" / "run_bpy_links.py"
-CONTRACT_MD = Path(__file__).resolve().parent / "CONTRACT.md"
-REST_PENETRATION_MAX_M = 0.005
-FK_TOL_M = 0.001
-
-#: every canonical artifact this build owns — staged together so a failed build
-#: can never leave a previous round's output looking current
-STAGED_OUTPUTS = ("build.json", "census.json", "meshes", "robot.urdf", "articulation.json", "object.glb")
-
-
-def _tail(s: str, n: int = 3000) -> str:
- return s[-n:] if s else ""
-
-
-class UrdfBlenderRuntime:
- language = Language.URDF_BLENDER
- entry_globs = (ENTRY_FILE[Language.URDF_BLENDER], "src/robot.urdf")
-
- # ------------------------------------------------------------ protocol
- def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
- if not isinstance(plan, ArticulatedPlan):
- raise TypeError(f"urdf_blender skeleton needs an ArticulatedPlan, got {type(plan).__name__}")
- return write_skeleton(ws, plan)
-
- def lint(self, ws: Workspace) -> GateReport:
- return lint_workspace(ws)
-
- def contract_doc(self) -> str:
- try:
- return load_text("urdf/contract.md")
- except FileNotFoundError:
- return CONTRACT_MD.read_text()
-
- def cookbook_path(self) -> Path:
- return PROMPTS_DIR / "urdf" / "cookbook.md"
-
- # ------------------------------------------------------------ build
- def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
- """All six canonical outputs go through one :class:`ArtifactStage`: entering
- it invalidates them BEFORE any early return can leak a previous round's
- files, everything is written to staging, and only an ``ok=True`` build
- promotes the full set. Every exit path publishes the FINAL BuildResult as
- ``artifacts/build.json`` — the wrapper's own build.json used to stay on disk
- saying ``ok: true`` while a post-wrapper check (UrdfError / FkInconsistent /
- RestPenetration) failed the build."""
- t0 = time.time()
- settings = get_settings()
- timeout_s = timeout_s or settings.limits.build_timeout_s
- ws.artifacts.mkdir(parents=True, exist_ok=True)
- with ws.stage_artifacts(*STAGED_OUTPUTS) as stage:
- return self._build_staged(ws, stage, t0=t0, settings=settings, timeout_s=timeout_s)
-
- def _build_staged(self, ws: Workspace, stage: ArtifactStage, *, t0: float, settings: Settings,
- timeout_s: int) -> BuildResult:
- art = ws.artifacts
-
- def finish(res: BuildResult) -> BuildResult:
- # disk never contradicts the returned result: build.json is ALWAYS the
- # final BuildResult; the rest of the set is published only on ok
- ws.write_json(stage.path("build.json"), res)
- if res.ok:
- stage.promote()
- elif stage.path("census.json").is_file():
- stage.promote("build.json", "census.json")
- else:
- stage.promote("build.json")
- return res
-
- def fail(error_type: str, message: str, *, file: str = "src/robot.urdf", line: int | None = None,
- census: dict[str, Any] | None = None, **kw: Any) -> BuildResult:
- return finish(BuildResult(ok=False, language=self.language.value, error_type=error_type,
- error_message=message, error_file=file, error_line=line,
- duration_ms=int((time.time() - t0) * 1000), census=census or {}, **kw))
-
- # 1. lint (cheap, no Blender)
- lint = self.lint(ws)
- census: dict[str, Any] = {"lint": [f.model_dump(mode="json") for f in lint.findings]}
- if not lint.passed:
- errs = lint.errors
- msg = "\n".join(f"- {f.message}" + (f" → {f.fix_hint}" if f.fix_hint else "") for f in errs[:12])
- return fail("LintError", f"{len(errs)} lint error(s):\n{msg}", file=str(errs[0].target or "src/robot.urdf"),
- line=errs[0].data.get("line"), census=census)
-
- # 2. Blender wrapper (writes build.json / census.json / meshes/ into the staging dir)
- blender = settings.resolve_blender()
- if not blender:
- return fail("BlenderNotFound", "no Blender binary (set CV3D_BINARIES__BLENDER)", file="", census=census)
- build_json, census_json = stage.path("build.json"), stage.path("census.json")
- proc = _run_blender(blender, ws, stage.staging_dir, timeout_s, settings.limits.bpy_rlimit_gb)
- if proc.timed_out:
- return fail("Timeout", f"Blender build exceeded {timeout_s}s (killed)", file="src/model.py", census=census,
- stdout_tail=_tail(proc.stdout), stderr_tail=_tail(proc.stderr))
- if not build_json.is_file():
- return fail("WrapperCrash", f"wrapper produced no build.json (exit {proc.returncode})", file="src/model.py",
- census=census, stdout_tail=_tail(proc.stdout), stderr_tail=_tail(proc.stderr))
- wb = read_json_file(build_json)
- wcensus = read_json_file(census_json) if census_json.is_file() else {}
- census.update({k: wcensus.get(k) for k in ("objects", "links", "unmatched_objects", "missing_links", "hints") if k in wcensus})
- if not wb.get("ok"):
- hints = "\n".join(f" hint: {h}" for h in (wcensus.get("hints") or {}).values())
- return fail(wb.get("error_type") or "ScriptError", (wb.get("error_message") or "") + ("\n" + hints if hints else ""),
- file=wb.get("error_file") or "src/model.py", line=wb.get("error_line"), census=census,
- stdout_tail=_tail(wb.get("stdout_tail", "") or proc.stdout),
- stderr_tail=_tail(wb.get("stderr_tail", "") or proc.stderr))
-
- # 3. URDF copy + load (staged files; extra_paths name the canonical homes)
- urdf_staged = stage.path("robot.urdf")
- shutil.copyfile(ws.root / "src" / "robot.urdf", urdf_staged)
- extra = {"urdf": str(art / "robot.urdf"), "meshes_dir": str(art / "meshes")}
- try:
- robot = load_urdf(urdf_staged, stage.path("meshes"))
- except UrdfError as e:
- return fail("UrdfError", str(e), census=census)
-
- # 4. FK consistency
- fk_findings = check_fk_consistency(robot, census.get("links") or {}, tol_m=FK_TOL_M)
- census["fk_check"] = [f.model_dump(mode="json") for f in fk_findings]
- if fk_findings:
- msg = "\n".join(f"- {f.as_line()}" for f in fk_findings)
- return fail("FkInconsistent", f"URDF frames do not reproduce the authored geometry:\n{msg}", census=census)
-
- # 5. pose sweep
- report = sweep_collisions(robot, pose_samples(robot, n_random=8, seed=0))
- findings = sweep_findings(report, rest_max_m=REST_PENETRATION_MAX_M)
- stage.path("articulation.json").write_text(json.dumps({"report": report.model_dump(mode="json"),
- "findings": [f.model_dump(mode="json") for f in findings]}, indent=1))
- extra["articulation"] = str(art / "articulation.json")
- for name, n in report.summary.link_islands.items():
- census.setdefault("links", {}).setdefault(name, {})["islands"] = n
- census["articulation"] = {"summary": report.summary.model_dump(mode="json"),
- "findings": [f.model_dump(mode="json") for f in findings],
- "n_joints": len(robot.joints), "movable_joints": [j.name for j in robot.movable_joints()]}
-
- # 6. canonical GLB at rest
- urdf_to_glb(robot, stage.path("object.glb"), None)
- extra["object_glb"] = str(art / "object.glb")
- res = BuildResult(ok=True, language=self.language.value, glb_path=str(art / "object.glb"), extra_paths=extra,
- stdout_tail=_tail(wb.get("stdout_tail", "")), duration_ms=int((time.time() - t0) * 1000), census=census)
- if report.summary.rest_max_penetration_m > REST_PENETRATION_MAX_M:
- worst = [f for f in findings if f.data.get("pose") == {} and f.severity == "error"]
- res.ok = False
- res.error_type = "RestPenetration"
- res.error_file = "src/model.py"
- res.error_message = (f"links interpenetrate by {report.summary.rest_max_penetration_m*1000:.1f} mm at the rest pose "
- f"(max {REST_PENETRATION_MAX_M*1000:.0f} mm):\n" +
- "\n".join(f"- {f.as_line()}" for f in worst[:8]))
- res.glb_path = None # the fresh GLB is NOT published on a failed build
- res.extra_paths = {}
- return finish(res)
-
-
-def _run_blender(blender: str, ws: Workspace, art: Path, timeout_s: int, rlimit_gb: int) -> ProcResult:
- cmd = [blender, "-b", "--factory-startup", "--python", str(WRAPPER), "--",
- "--script", str(ws.root / "src" / "model.py"), "--urdf", str(ws.root / "src" / "robot.urdf"),
- "--out", str(art), "--rlimit-gb", str(rlimit_gb)]
- # whitelist env (no inherited PYTHONPATH, user config pinned into artifacts) — deliberately
- # stricter than blender.runtime.blender_env(); keep it that way
- env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": os.environ.get("HOME", str(ws.root)),
- "PYTHONDONTWRITEBYTECODE": "1", "PYTHONNOUSERSITE": "1", "BLENDER_USER_CONFIG": str(art / ".blender_config")}
- return run_subprocess(cmd, cwd=ws.root, env=env, timeout_s=timeout_s)
diff --git a/harness/codeverse/languages/urdf/skeleton.py b/harness/codeverse/languages/urdf/skeleton.py
deleted file mode 100644
index 9dd18f62..00000000
--- a/harness/codeverse/languages/urdf/skeleton.py
+++ /dev/null
@@ -1,224 +0,0 @@
-"""Starter files for ``urdf_blender`` from an :class:`ArticulatedPlan`.
-
-Writes a RUNNABLE ``src/model.py`` (one placeholder box per link at the plan
-bbox, named exactly like the link) and a CORRECT ``src/robot.urdf`` whose joint
-origins / visual origins follow the enforced convention (see CONTRACT.md):
-
-* root link frame = world origin;
-* every other link frame = its parent joint's pivot (world), no rotation;
-* joint ``<origin xyz>`` = pivot_world(child) − link_frame_world(parent);
-* visual ``<origin xyz>`` = −link_frame_world(link) (meshes are exported in
- world coordinates at the authored rest pose);
-* URDF ``q = 0`` is the authored rest pose (the pose the plan's bboxes / pivots
- describe), so plan limits are shifted by ``rest``: ``lower-rest .. upper-rest``
- (identical to the plan's when ``rest == 0``, the usual case). The rendered URDF
- says so in a comment next to every shifted ``<limit>`` so the agent who reads the
- plan table (unshifted values) and the skeleton sees one consistent rule.
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from pathlib import Path
-
-from codeverse.contracts.plan import ArticulatedPlan, JointPlan, PartPlan
-from codeverse.conventions import to_snake
-from codeverse.workspace import Workspace
-
-DEFAULT_EFFORT = 10.0
-DEFAULT_VELOCITY = 1.0
-
-
-@dataclass(frozen=True)
-class LinkFrame:
- """World placement of one link frame at rest + its plan bbox."""
-
- name: str
- frame_xyz: tuple[float, float, float]
- bbox_center: tuple[float, float, float]
- bbox_extents: tuple[float, float, float]
- parent_joint: str | None
-
-
-@dataclass(frozen=True)
-class JointRow:
- name: str
- type: str
- parent: str
- child: str
- origin_xyz: tuple[float, float, float]
- axis: tuple[float, float, float]
- lower: float | None
- upper: float | None
- rest: float = 0.0 # plan rest value the limits were shifted by (0 → limits == plan limits)
-
-
-@dataclass
-class UrdfFrames:
- robot_name: str
- root: str
- links: dict[str, LinkFrame]
- joints: list[JointRow]
-
-
-def _fmt(v: float) -> str:
- s = f"{v:.6f}".rstrip("0").rstrip(".")
- return "0" if s in ("", "-0") else s
-
-
-def _vec(v: tuple[float, float, float]) -> str:
- return " ".join(_fmt(x) for x in v)
-
-
-def _expand_parts(plan: ArticulatedPlan) -> list[tuple[str, PartPlan, tuple[float, float, float]]]:
- """(link_name, part, bbox_center) — parts with ``instances > 1`` become ``<name>_1..n``
- spread along +x so the baseline has no overlaps (the agent repositions them)."""
- out = []
- for p in plan.parts:
- base = to_snake(p.name)
- if p.instances <= 1:
- out.append((base, p, tuple(p.bbox.center)))
- continue
- cx, cy, cz = p.bbox.center
- step = p.bbox.extents[0] * 1.5
- for i in range(p.instances):
- out.append((f"{base}_{i + 1}", p, (cx + i * step, cy, cz)))
- return out
-
-
-def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
- """Pure function: plan → link frames + joint rows in the enforced convention."""
- parts = _expand_parts(plan)
- base_names = {to_snake(p.name) for p in plan.parts}
- instance_links = {n for n, p, _ in parts if p.instances > 1}
- root = to_snake(plan.root_link)
- links: dict[str, LinkFrame] = {}
- pivot_of: dict[str, tuple[float, float, float]] = {}
- parent_of: dict[str, str] = {}
- joints: list[JointRow] = []
-
- offsets = {n: tuple(c - o for c, o in zip(center, p.bbox.center, strict=True)) for n, p, center in parts}
-
- def add_joint(j: JointPlan, child: str, parent: str, suffix: str = "") -> None:
- pivot_of[child] = tuple(float(v) + o for v, o in zip(j.pivot, offsets[child], strict=True))
- parent_of[child] = parent
- lower = upper = None
- if j.type in ("revolute", "prismatic"):
- lower, upper = j.lower - j.rest, j.upper - j.rest
- joints.append(JointRow(name=to_snake(j.name) + suffix, type=j.type, parent=parent, child=child,
- origin_xyz=(0.0, 0.0, 0.0), axis=tuple(float(v) for v in j.axis), lower=lower, upper=upper,
- rest=float(j.rest) if lower is not None else 0.0))
-
- for j in plan.joints:
- parent, child = to_snake(j.parent), to_snake(j.child)
- if parent in base_names and parent not in {n for n, _, _ in parts}:
- parent = f"{parent}_1" # joint to an instanced parent → first instance
- children = [n for n, p, _ in parts if n == child or (n in instance_links and n.rsplit("_", 1)[0] == child)]
- for k, c in enumerate(children):
- add_joint(j, c, parent, "" if len(children) == 1 else f"_{k + 1}")
-
- # link frames: root at origin, others at their pivot
- for name, p, center in parts:
- frame = (0.0, 0.0, 0.0) if name == root else pivot_of.get(name, (0.0, 0.0, 0.0))
- pj = next((jr.name for jr in joints if jr.child == name), None)
- links[name] = LinkFrame(name=name, frame_xyz=frame, bbox_center=center,
- bbox_extents=tuple(float(v) for v in p.bbox.extents), parent_joint=pj)
- # joint origins relative to the parent link frame
- fixed: list[JointRow] = []
- for jr in joints:
- pf = links[jr.parent].frame_xyz
- cf = links[jr.child].frame_xyz
- fixed.append(JointRow(name=jr.name, type=jr.type, parent=jr.parent, child=jr.child,
- origin_xyz=tuple(c - p for c, p in zip(cf, pf, strict=True)), axis=jr.axis,
- lower=jr.lower, upper=jr.upper, rest=jr.rest))
- return UrdfFrames(robot_name=to_snake(plan.object_name), root=root, links=links, joints=fixed)
-
-
-# ------------------------------------------------------------------ text renderers
-def _limit_note(jr: JointRow) -> str:
- """Comment explaining a rest-shifted limit (empty when the plan's rest is 0)."""
- if jr.lower is None or jr.upper is None or abs(jr.rest) < 1e-12:
- return ""
- return (f" <!-- plan lower={_fmt(jr.lower + jr.rest)} upper={_fmt(jr.upper + jr.rest)} rest={_fmt(jr.rest)}: "
- f"the mesh is authored at rest, so q=0 = plan {_fmt(jr.rest)} and the limits are shifted by -rest -->")
-
-
-def render_urdf(frames: UrdfFrames) -> str:
- lines = ['<?xml version="1.0"?>', f'<robot name="{frames.robot_name}">']
- lines.append(" <!-- link frames: root at the world origin; every other link frame sits at its joint pivot (world, rest pose). -->")
- lines.append(" <!-- visual/collision origin = -(link frame world) because meshes/<link>.glb hold WORLD coordinates at rest. -->")
- lines.append(" <!-- q=0 is the authored pose (the plan's rest pose); limits are the plan's lower-rest .. upper-rest. -->")
- for name, lf in frames.links.items():
- vis = tuple(-v for v in lf.frame_xyz)
- lines.append(f' <link name="{name}"> <!-- frame at world {_vec(lf.frame_xyz)} -->')
- for tag in ("visual", "collision"):
- lines.append(f' <{tag}><origin xyz="{_vec(vis)}" rpy="0 0 0"/><geometry><mesh filename="meshes/{name}.glb"/></geometry></{tag}>')
- lines.append(" </link>")
- for jr in frames.joints:
- lines.append(f' <joint name="{jr.name}" type="{jr.type}">')
- lines.append(f' <parent link="{jr.parent}"/>')
- lines.append(f' <child link="{jr.child}"/>')
- lines.append(f' <origin xyz="{_vec(jr.origin_xyz)}" rpy="0 0 0"/> <!-- pivot_world(child) - frame_world(parent) -->')
- if jr.type != "fixed":
- lines.append(f' <axis xyz="{_vec(jr.axis)}"/>')
- lim = f'effort="{_fmt(DEFAULT_EFFORT)}" velocity="{_fmt(DEFAULT_VELOCITY)}"'
- if jr.lower is not None and jr.upper is not None:
- lim = f'lower="{_fmt(jr.lower)}" upper="{_fmt(jr.upper)}" ' + lim
- lines.append(f" <limit {lim}/>" + _limit_note(jr))
- lines.append(" </joint>")
- lines.append("</robot>")
- return "\n".join(lines) + "\n"
-
-
-def render_model_py(plan: ArticulatedPlan, frames: UrdfFrames) -> str:
- parts_by_link = {n: p for n, p, _ in _expand_parts(plan)}
- head = f'''"""{plan.object_name} — link meshes for robot.urdf (pure bpy, Z-up, -Y front, meters).
-
-CONTRACT: build ONE mesh object per URDF link, named EXACTLY like the link, placed
-at its REST-POSE WORLD position (= URDF q=0, the pose the plan's bboxes describe).
-Extra helper objects must be parented under a link object (they are joined into
-it). No cameras / lights / render / export calls.
-Replace every placeholder box below with real, detailed geometry; keep the names.
-"""
-import bpy
-import bmesh # noqa: F401 (handy for detail)
-import math # noqa: F401
-from mathutils import Vector # noqa: F401
-
-
-def box(name, center, size):
- """Axis-aligned box helper: center/size in world meters; returns the object."""
- bpy.ops.mesh.primitive_cube_add(size=1.0, location=center)
- ob = bpy.context.active_object
- ob.name = name
- ob.scale = size
- bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
- return ob
-
-
-'''
- body = []
- for name, lf in frames.links.items():
- p = parts_by_link[name]
- role = (p.role or "").replace("\n", " ")
- desc = (p.description or "").replace("\n", " ")
- body.append(f"# link '{name}': {role}\n# {desc}")
- if lf.parent_joint:
- jr = next(j for j in frames.joints if j.name == lf.parent_joint)
- note = f" (plan rest={_fmt(jr.rest)} → this pose is URDF q=0)" if abs(jr.rest) > 1e-12 else ""
- body.append(f"# joint '{lf.parent_joint}' pivot (world) = {lf.frame_xyz}{note}")
- body.append(f"{name} = box({name!r}, center={tuple(round(v, 4) for v in lf.bbox_center)}, "
- f"size={tuple(round(v, 4) for v in lf.bbox_extents)})\n")
- tail = f"\n# Sanity: every link object exists\nfor _n in {list(frames.links)!r}:\n assert _n in bpy.data.objects, _n\n"
- return head + "\n".join(body) + tail
-
-
-def write_skeleton(ws: Workspace, plan: ArticulatedPlan) -> list[Path]:
- """Write src/model.py + src/robot.urdf; returns the written paths."""
- frames = compute_urdf_frames(plan)
- ws.src.mkdir(parents=True, exist_ok=True)
- model = ws.src / "model.py"
- urdf = ws.src / "robot.urdf"
- model.write_text(render_model_py(plan, frames))
- urdf.write_text(render_urdf(frames))
- return [model, urdf]
diff --git a/harness/codeverse/skills/_claims/cv3d-urdf-joints.toml b/harness/codeverse/skills/_claims/cv3d-urdf-joints.toml
index 98c661d8..f872138f 100644
--- a/harness/codeverse/skills/_claims/cv3d-urdf-joints.toml
+++ b/harness/codeverse/skills/_claims/cv3d-urdf-joints.toml
@@ -10,9 +10,9 @@ python = "codeverse.conventions:CONTACT_GAP_M"
[[claim]]
key = "fk_tol_m"
text = "0.001"
-python = "codeverse.languages.urdf.runtime:FK_TOL_M"
+python = "codeverse.languages.urdf:FK_TOL_M"
[[claim]]
key = "rest_penetration_max_m"
text = "0.005"
-python = "codeverse.languages.urdf.runtime:REST_PENETRATION_MAX_M"
+python = "codeverse.languages.urdf:REST_PENETRATION_MAX_M"
diff --git a/harness/codeverse/skills/cv3d-glsl-craft/references/shader-recipes.md b/harness/codeverse/skills/cv3d-glsl-craft/references/shader-recipes.md
index a34d635c..88952108 100644
--- a/harness/codeverse/skills/cv3d-glsl-craft/references/shader-recipes.md
+++ b/harness/codeverse/skills/cv3d-glsl-craft/references/shader-recipes.md
@@ -1,7 +1,7 @@
# Shader recipes
Companion to `cv3d-glsl-craft`. Every snippet below was composed with the harness's own
-`codeverse.languages.glsl_shader.wrap.compose`, compiled on moderngl 5.12 / OpenGL 3.3 core
+`codeverse.languages.glsl_shader.compose`, compiled on moderngl 5.12 / OpenGL 3.3 core
and linted with `lint_text` on 2026-08-25: **compiles clean, zero lint findings**. Drop the
helpers into `src/common.glsl` and call them from `src/shader.frag`.
diff --git a/harness/codeverse/tracks/common.py b/harness/codeverse/tracks/common.py
index bf75dbfb..8e05bc72 100644
--- a/harness/codeverse/tracks/common.py
+++ b/harness/codeverse/tracks/common.py
@@ -152,7 +152,7 @@ class Services:
# ---- scene assembly + record
def assemble_scene(self, ws: Workspace, plan: Plan) -> Any:
- fn = _import("codeverse.languages.scene_threejs.assemble", "assemble")
+ fn = _import("codeverse.languages.scene_threejs", "assemble")
return fn(ws, plan, cameras="plan" if getattr(plan, "cameras", None) else "derive")
def finalize_record(self, ws: Workspace, record: RunRecord) -> None:
diff --git a/harness/codeverse/tracks/graphics.py b/harness/codeverse/tracks/graphics.py
index bda8da6c..64c96544 100644
--- a/harness/codeverse/tracks/graphics.py
+++ b/harness/codeverse/tracks/graphics.py
@@ -32,9 +32,7 @@ from codeverse.contracts.plan import AcceptanceItem, GraphicsPlan, Plan
from codeverse.contracts.run import RoundRecord
from codeverse.contracts.spec import Spec
from codeverse.languages._gl_common import SHEET_NAME, read_metrics
-from codeverse.languages.glsl_shader.lint import FUNC_DEF
-from codeverse.languages.glsl_shader.skeleton import COMMON_GLSL
-from codeverse.languages.glsl_shader.wrap import strip_comments
+from codeverse.languages.glsl_shader import COMMON_GLSL, FUNC_DEF, strip_comments
from codeverse.orchestrator import TaskGroup
from codeverse.prompts import render
from codeverse.spatial.cookbook_tool import Section, split_sections
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index adc73bb1..1f63ec1f 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -106,9 +106,10 @@ codeverse/
(gemini-cli / claude-code / codex / antigravity), cli_common.py (sessions,
the watchdog clocks, the transcript, retry trajectory naming,
files_changed attribution), materialize.py
- languages/ LanguageRuntime (base.py); blender/ (multi-file: layout.py, model.py + parts/*.py) cadquery/
- threejs/ (+ templates.py) urdf/ scene_threejs/ glsl_shader/ (wrap.py header+line-map)
- opengl_python/ (wrappers/run_gl.py) — each runtime.py, lint.py, skeleton.py, wrappers/;
+ languages/ LanguageRuntime (base.py); one merged module per language since 2026-08-28 —
+ blender/ cadquery/ threejs/ urdf/ scene_threejs/ glsl_shader/ opengl_python/ are each
+ a single __init__.py (lint → skeleton → runtime, in dependency order) beside their
+ data (wrappers/, starter/, CONTRACT.md — Path(__file__) assets unchanged);
file_lint.py (one just-written file → syntax/lint verdict for write_file, COST.md §29)
spatial/ node.py, render.py, tool_common.py (shared tool plumbing), cookbook_tool.py
(read_cookbook), render_scene.py (judge view subset, content-fitted orbit),
diff --git a/harness/tests/blender_cadquery/test_blender_layout.py b/harness/tests/blender_cadquery/test_blender_layout.py
index 104c6792..95e24fb2 100644
--- a/harness/tests/blender_cadquery/test_blender_layout.py
+++ b/harness/tests/blender_cadquery/test_blender_layout.py
@@ -7,14 +7,14 @@ import importlib.util
import sys
from pathlib import Path
-from codeverse.languages.blender.layout import (
+from codeverse.languages.blender import (
+ WRAPPER,
build_fn_name,
lint_workspace,
part_file_rel,
part_files,
source_files,
)
-from codeverse.languages.blender.runtime import WRAPPER
SEAT = '''import bpy, bmesh
diff --git a/harness/tests/blender_cadquery/test_blender_lint.py b/harness/tests/blender_cadquery/test_blender_lint.py
index b4aab894..0764e5b6 100644
--- a/harness/tests/blender_cadquery/test_blender_lint.py
+++ b/harness/tests/blender_cadquery/test_blender_lint.py
@@ -5,7 +5,7 @@ from __future__ import annotations
from pathlib import Path
from codeverse.contracts.artifacts import Severity
-from codeverse.languages.blender.lint import lint_blender_file, lint_blender_source
+from codeverse.languages.blender import lint_blender_file, lint_blender_source
GOOD = '''
import bpy
diff --git a/harness/tests/blender_cadquery/test_blender_live_gates.py b/harness/tests/blender_cadquery/test_blender_live_gates.py
index 23dbcb7a..7d1b6c87 100644
--- a/harness/tests/blender_cadquery/test_blender_live_gates.py
+++ b/harness/tests/blender_cadquery/test_blender_live_gates.py
@@ -13,8 +13,7 @@ import subprocess
import pytest
from codeverse.contracts.artifacts import Severity
-from codeverse.languages.blender.lint import REMOVED_BSDF_INPUTS
-from codeverse.languages.blender.runtime import BlenderRuntime, blender_env
+from codeverse.languages.blender import REMOVED_BSDF_INPUTS, BlenderRuntime, blender_env
pytestmark = pytest.mark.blender
diff --git a/harness/tests/blender_cadquery/test_blender_multifile.py b/harness/tests/blender_cadquery/test_blender_multifile.py
index 45c3cefc..9b755cf7 100644
--- a/harness/tests/blender_cadquery/test_blender_multifile.py
+++ b/harness/tests/blender_cadquery/test_blender_multifile.py
@@ -11,7 +11,7 @@ from pathlib import Path
import pytest
from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
-from codeverse.languages.blender.runtime import BlenderRuntime
+from codeverse.languages.blender import BlenderRuntime
from codeverse.prompts import PROMPTS_DIR
from codeverse.workspace import Workspace
diff --git a/harness/tests/blender_cadquery/test_blender_runtime.py b/harness/tests/blender_cadquery/test_blender_runtime.py
index 51799865..9e8050f8 100644
--- a/harness/tests/blender_cadquery/test_blender_runtime.py
+++ b/harness/tests/blender_cadquery/test_blender_runtime.py
@@ -12,12 +12,12 @@ import pytest
from codeverse.contracts.artifacts import BuildResult
from codeverse.languages import get_runtime
from codeverse.languages.base import LanguageRuntime
-from codeverse.languages.blender.lint import lint_blender_file
-from codeverse.languages.blender.runtime import (
+from codeverse.languages.blender import (
WRAPPER,
BlenderNotFoundError,
BlenderRuntime,
blender_env,
+ lint_blender_file,
)
FAKE_BLENDER = """#!/usr/bin/env python3
diff --git a/harness/tests/blender_cadquery/test_blender_skeleton.py b/harness/tests/blender_cadquery/test_blender_skeleton.py
index dc1eceb4..cd02aeb8 100644
--- a/harness/tests/blender_cadquery/test_blender_skeleton.py
+++ b/harness/tests/blender_cadquery/test_blender_skeleton.py
@@ -5,12 +5,12 @@ from __future__ import annotations
import ast
from codeverse.contracts.plan import BBox
-from codeverse.languages.blender.layout import lint_workspace
-from codeverse.languages.blender.lint import lint_blender_source
-from codeverse.languages.blender.skeleton import (
+from codeverse.languages.blender import (
blender_skeleton_source,
finish_for,
instance_centers,
+ lint_blender_source,
+ lint_workspace,
model_file_source,
part_file_source,
write_blender_skeleton,
diff --git a/harness/tests/blender_cadquery/test_cadquery_lint.py b/harness/tests/blender_cadquery/test_cadquery_lint.py
index f9fee452..1b444fff 100644
--- a/harness/tests/blender_cadquery/test_cadquery_lint.py
+++ b/harness/tests/blender_cadquery/test_cadquery_lint.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import pytest
from codeverse.contracts.artifacts import Severity
-from codeverse.languages.cadquery.lint import lint_cadquery_source
+from codeverse.languages.cadquery import lint_cadquery_source
GOOD = '''
import cadquery as cq
diff --git a/harness/tests/blender_cadquery/test_cadquery_runtime.py b/harness/tests/blender_cadquery/test_cadquery_runtime.py
index 48712d73..b95554c6 100644
--- a/harness/tests/blender_cadquery/test_cadquery_runtime.py
+++ b/harness/tests/blender_cadquery/test_cadquery_runtime.py
@@ -14,9 +14,13 @@ import pytest
from codeverse.languages import get_runtime
from codeverse.languages.base import LanguageRuntime
-from codeverse.languages.cadquery.lint import lint_cadquery_source
-from codeverse.languages.cadquery.runtime import WRAPPER, CadQueryRuntime, cadquery_env
-from codeverse.languages.cadquery.skeleton import cadquery_skeleton_source
+from codeverse.languages.cadquery import (
+ WRAPPER,
+ CadQueryRuntime,
+ cadquery_env,
+ cadquery_skeleton_source,
+ lint_cadquery_source,
+)
from tests.blender_cadquery.conftest import has_cadquery
needs_cq = pytest.mark.skipif(not has_cadquery(), reason="cadquery not importable")
diff --git a/harness/tests/blender_cadquery/test_prompt_block_lint.py b/harness/tests/blender_cadquery/test_prompt_block_lint.py
index cd8de4c6..c87a0f58 100644
--- a/harness/tests/blender_cadquery/test_prompt_block_lint.py
+++ b/harness/tests/blender_cadquery/test_prompt_block_lint.py
@@ -14,8 +14,8 @@ from pathlib import Path
import pytest
-from codeverse.languages.blender.lint import lint_blender_source
-from codeverse.languages.cadquery.lint import lint_cadquery_source
+from codeverse.languages.blender import lint_blender_source
+from codeverse.languages.cadquery import lint_cadquery_source
PROMPTS = Path(__file__).resolve().parents[2] / "codeverse" / "prompts"
FENCE = re.compile(r"^```(?:py|python)\s*$(.*?)^```\s*$", re.M | re.S)
diff --git a/harness/tests/core/test_portability.py b/harness/tests/core/test_portability.py
index 33ec6e85..beae8414 100644
--- a/harness/tests/core/test_portability.py
+++ b/harness/tests/core/test_portability.py
@@ -87,7 +87,7 @@ def test_package_data_ships_every_file_a_runtime_reads() -> None:
def test_write_example_refuses_to_write_nothing(tmp_path, monkeypatch) -> None:
"""The other half of PORT-4: an install without the starter tree must fail loudly at
the moment it is needed, not hand back an empty scene."""
- from codeverse.languages.scene_threejs import skeleton
+ import codeverse.languages.scene_threejs as skeleton
monkeypatch.setattr(skeleton, "STARTER_DIR", tmp_path / "gone" / "src")
with pytest.raises(FileNotFoundError, match="starter tree missing"):
diff --git a/harness/tests/graphics/test_gl_runtime.py b/harness/tests/graphics/test_gl_runtime.py
index 66c4e9e8..f3600b37 100644
--- a/harness/tests/graphics/test_gl_runtime.py
+++ b/harness/tests/graphics/test_gl_runtime.py
@@ -7,8 +7,8 @@ import json
import pytest
from codeverse.contracts.plan import GraphicsPlan, PassPlan
-from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
-from codeverse.languages.opengl_python.runtime import OpenGLPythonRuntime
+from codeverse.languages.glsl_shader import GlslShaderRuntime
+from codeverse.languages.opengl_python import OpenGLPythonRuntime
from codeverse.spatial.gl_render import GlHost, GlHostError
from codeverse.spatial.registry import ToolContext, get_tool
@@ -103,7 +103,7 @@ def test_program_skeleton_builds_and_errors_map(tmp_ws, host):
def test_gl_tools_probe_and_frames(tmp_ws, host, monkeypatch):
ws = _ws_with_plan(tmp_ws)
GlslShaderRuntime(host=host).skeleton(ws, PLAN)
- monkeypatch.setattr("codeverse.languages.glsl_shader.runtime.GlslShaderRuntime.host", lambda self, timeout_s=None: host)
+ monkeypatch.setattr("codeverse.languages.glsl_shader.GlslShaderRuntime.host", lambda self, timeout_s=None: host)
ctx = ToolContext(workspace=ws, language="glsl_shader", track="graphics")
obs = get_tool("gl_probe").call(ctx, {"t": 1.5})
assert obs.ok and "PROBE OK" in obs.text and len(obs.images) == 1 and obs.numbers["n_frames"] == 1
@@ -122,7 +122,7 @@ def test_gl_probe_compile_error_report(tmp_ws, host, monkeypatch):
(ws.src / "shader.frag").write_text(
"// line 1\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n"
" float v = twice(nope);\n fragColor = vec4(uv, v, 1.0);\n}\n")
- monkeypatch.setattr("codeverse.languages.glsl_shader.runtime.GlslShaderRuntime.host", lambda self, timeout_s=None: host)
+ monkeypatch.setattr("codeverse.languages.glsl_shader.GlslShaderRuntime.host", lambda self, timeout_s=None: host)
ctx = ToolContext(workspace=ws, language="glsl_shader", track="graphics")
obs = get_tool("gl_probe").call(ctx, {})
assert not obs.ok and obs.numbers["stage"] == "build"
diff --git a/harness/tests/graphics/test_live.py b/harness/tests/graphics/test_live.py
index 4dc41c98..74156a64 100644
--- a/harness/tests/graphics/test_live.py
+++ b/harness/tests/graphics/test_live.py
@@ -10,7 +10,7 @@ from codeverse.contracts.plan import GraphicsPlan
from codeverse.contracts.spec import Spec
from codeverse.judges.base import JudgeInput
from codeverse.judges.vlm_judge import VlmJudge
-from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
+from codeverse.languages.glsl_shader import GlslShaderRuntime
from codeverse.tracks.generation import generate_files
from codeverse.tracks.graphics import (
GraphicsTrack,
diff --git a/harness/tests/graphics/test_stale_invalidation.py b/harness/tests/graphics/test_stale_invalidation.py
index 9ed93201..bab0de96 100644
--- a/harness/tests/graphics/test_stale_invalidation.py
+++ b/harness/tests/graphics/test_stale_invalidation.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import json
import codeverse.spatial.tools # noqa: F401 — registers the gl_* tools
-from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
+from codeverse.languages.glsl_shader import GlslShaderRuntime
from codeverse.spatial.gl_render import GlResult
from codeverse.spatial.registry import ToolContext, get_tool
from codeverse.workspace import Workspace
diff --git a/harness/tests/graphics/test_track.py b/harness/tests/graphics/test_track.py
index ee9ebc6a..7c0b993e 100644
--- a/harness/tests/graphics/test_track.py
+++ b/harness/tests/graphics/test_track.py
@@ -18,8 +18,7 @@ from codeverse.contracts.run import RunStatus
from codeverse.contracts.spec import Constraints, Spec
from codeverse.judges.rubrics import load_rubric
from codeverse.languages._gl_common import finish_build, judge_times, preview_times
-from codeverse.languages.glsl_shader.lint import lint_workspace
-from codeverse.languages.glsl_shader.skeleton import write_skeleton
+from codeverse.languages.glsl_shader import lint_workspace, write_skeleton
from codeverse.proc import EventLog
from codeverse.prompts import render
from codeverse.spatial.gl_render import GlFrame, GlResult
diff --git a/harness/tests/graphics/test_wrap_lint.py b/harness/tests/graphics/test_wrap_lint.py
index 4c7fa9a8..8c905cc1 100644
--- a/harness/tests/graphics/test_wrap_lint.py
+++ b/harness/tests/graphics/test_wrap_lint.py
@@ -3,16 +3,17 @@
from __future__ import annotations
from codeverse.contracts.artifacts import Severity
-from codeverse.languages.glsl_shader.lint import lint_text, lint_workspace
-from codeverse.languages.glsl_shader.wrap import (
+from codeverse.languages.glsl_shader import (
HEADER,
compose,
detect_convention,
first_error,
+ lint_text,
+ lint_workspace,
parse_glsl_log,
)
-from codeverse.languages.opengl_python.lint import lint_source
-from codeverse.languages.opengl_python.lint import lint_workspace as lint_program_ws
+from codeverse.languages.opengl_python import lint_source
+from codeverse.languages.opengl_python import lint_workspace as lint_program_ws
SHADER = "void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n vec2 uv = fragCoord / u_resolution.xy;\n fragColor = vec4(uv, 0.5 + 0.5*sin(u_time), 1.0);\n}\n"
COMMON = "float hash(float n) { return fract(sin(n) * 43758.5453); }\n"
diff --git a/harness/tests/languages/test_ast_lint.py b/harness/tests/languages/test_ast_lint.py
index 1fa49840..dbe04b5c 100644
--- a/harness/tests/languages/test_ast_lint.py
+++ b/harness/tests/languages/test_ast_lint.py
@@ -4,11 +4,11 @@ from __future__ import annotations
import ast
+import codeverse.languages.blender as blender_lint
+import codeverse.languages.cadquery as cadquery_lint
+import codeverse.languages.opengl_python as opengl_lint
from codeverse.contracts.artifacts import GateFinding, Severity
from codeverse.languages._ast_lint import BASE_FORBIDDEN_IMPORTS, check_imports, dotted
-from codeverse.languages.blender import lint as blender_lint
-from codeverse.languages.cadquery import lint as cadquery_lint
-from codeverse.languages.opengl_python import lint as opengl_lint
# ----------------------------------------------------------------- superset (drift fails here)
@@ -115,10 +115,10 @@ def test_every_python_lint_survives_a_parser_crash(monkeypatch):
import ast
from codeverse.contracts.artifacts import Severity
- from codeverse.languages.blender.lint import lint_blender_source
- from codeverse.languages.cadquery.lint import lint_cadquery_source
- from codeverse.languages.opengl_python.lint import lint_source as lint_gl
- from codeverse.languages.urdf.lint import lint_model_text
+ from codeverse.languages.blender import lint_blender_source
+ from codeverse.languages.cadquery import lint_cadquery_source
+ from codeverse.languages.opengl_python import lint_source as lint_gl
+ from codeverse.languages.urdf import lint_model_text
real = ast.parse
@@ -141,7 +141,7 @@ def test_every_python_lint_survives_a_parser_crash(monkeypatch):
def test_real_deeply_nested_source_does_not_escape_the_lint():
"""A 40 000-term binary chain: on 3.11 this is the SystemError, on 3.12+ a RecursionError,
on some builds a plain SyntaxError — whichever, the lint returns a report."""
- from codeverse.languages.blender.lint import lint_blender_source
+ from codeverse.languages.blender import lint_blender_source
deep = "import bpy\nx = " + " + ".join(["1"] * 40_000) + "\n"
rep = lint_blender_source(deep)
diff --git a/harness/tests/languages/test_gl_common_entry.py b/harness/tests/languages/test_gl_common_entry.py
index 5a7eb7f6..0cde715e 100644
--- a/harness/tests/languages/test_gl_common_entry.py
+++ b/harness/tests/languages/test_gl_common_entry.py
@@ -2,9 +2,9 @@
from __future__ import annotations
+import codeverse.languages.glsl_shader as wrap
from codeverse.contracts.common import ENTRY_FILE, Language
from codeverse.languages import _gl_common
-from codeverse.languages.glsl_shader import wrap
from codeverse.spatial.gl_render import GlHost
@@ -22,13 +22,12 @@ def test_make_host_prefers_injected_host() -> None:
def test_runtimes_lead_with_the_entry_file_table() -> None:
- from codeverse.languages.blender.layout import ENTRY_REL
- from codeverse.languages.blender.runtime import BlenderRuntime
- from codeverse.languages.cadquery.runtime import CadQueryRuntime
- from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
- from codeverse.languages.opengl_python.runtime import OpenGLPythonRuntime
- from codeverse.languages.threejs.runtime import ThreeJsRuntime
- from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+ from codeverse.languages.blender import ENTRY_REL, BlenderRuntime
+ from codeverse.languages.cadquery import CadQueryRuntime
+ from codeverse.languages.glsl_shader import GlslShaderRuntime
+ from codeverse.languages.opengl_python import OpenGLPythonRuntime
+ from codeverse.languages.threejs import ThreeJsRuntime
+ from codeverse.languages.urdf import UrdfBlenderRuntime
assert ENTRY_FILE[Language.BLENDER] == ENTRY_REL
for rt in (BlenderRuntime, CadQueryRuntime, GlslShaderRuntime, OpenGLPythonRuntime,
diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.py
index 125cc5d4..0a342854 100644
--- a/harness/tests/models/test_gemini.py
+++ b/harness/tests/models/test_gemini.py
@@ -691,3 +691,29 @@ def test_ipv4_transport_toggle(monkeypatch):
assert isinstance(args["transport"], httpx.HTTPTransport)
monkeypatch.setenv("CV3D_IPV4", "0")
assert _ipv4_client_args() == {}
+
+
+def test_merge_stream_chunks_carries_tool_calls_and_signatures():
+ """Tool calls stream as function_call parts; the merge must keep them in arrival
+ order next to the text parts, and extract_candidate must still mint/pair ids and
+ stash thought signatures — the text-only tests above never exercised this."""
+ from codeverse.models.gemini import _merge_stream_chunks
+
+ fc = types.Part(function_call=types.FunctionCall(name="measure", args={"part": "Hull"}))
+ fc.thought_signature = b"sig-bytes"
+ c1 = types.GenerateContentResponse(
+ candidates=[types.Candidate(content=types.Content(role="model", parts=[types.Part.from_text(text="checking ")]))])
+ c2 = types.GenerateContentResponse(
+ candidates=[types.Candidate(content=types.Content(role="model", parts=[fc]), finish_reason="STOP")],
+ usage_metadata=types.GenerateContentResponseUsageMetadata(prompt_token_count=9, candidates_token_count=4))
+ merged = _merge_stream_chunks([c1, c2])
+ text, calls, finish = extract_candidate_for_test(merged)
+ assert text == "checking " and finish == "STOP"
+ assert len(calls) == 1 and calls[0].name == "measure" and calls[0].arguments == {"part": "Hull"}
+ assert SIGNATURES.get(calls[0].id) == b"sig-bytes"
+
+
+def extract_candidate_for_test(resp):
+ from codeverse.models.gemini import extract_candidate
+
+ return extract_candidate(resp)
diff --git a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py
index 0cba5023..ad7736dd 100644
--- a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py
+++ b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py
@@ -113,7 +113,7 @@ def test_graphics_prompt_context_uses_the_selector(monkeypatch) -> None:
def test_aurora_example_ships_and_composes() -> None:
- from codeverse.languages.glsl_shader.wrap import compose
+ from codeverse.languages.glsl_shader import compose
assert EXAMPLE.is_file(), EXAMPLE
src = EXAMPLE.read_text()
diff --git a/harness/tests/orchestrator_tracks/test_graphics_recipes.py b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
index 99ed3d03..5afa4e06 100644
--- a/harness/tests/orchestrator_tracks/test_graphics_recipes.py
+++ b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
@@ -22,11 +22,17 @@ from codeverse.config import Settings, seed_recipes_enabled
from codeverse.contracts.common import HARNESS_OWNED_SRC, Language, Track
from codeverse.contracts.plan import GraphicsPlan
from codeverse.languages.file_lint import lint_one_file
-from codeverse.languages.glsl_shader.lint import lint_text, lint_workspace
-from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
-from codeverse.languages.glsl_shader.skeleton import COMMON_GLSL, write_skeleton
-from codeverse.languages.glsl_shader.wrap import HEADER as WRAP_HEADER
-from codeverse.languages.glsl_shader.wrap import compose, first_error, parse_glsl_log
+from codeverse.languages.glsl_shader import (
+ COMMON_GLSL,
+ GlslShaderRuntime,
+ compose,
+ first_error,
+ lint_text,
+ lint_workspace,
+ parse_glsl_log,
+ write_skeleton,
+)
+from codeverse.languages.glsl_shader import HEADER as WRAP_HEADER
from codeverse.proc import EventLog
from codeverse.prompts import load_text, render
from codeverse.tracks import graphics as gr
diff --git a/harness/tests/prompts/test_snippets_run.py b/harness/tests/prompts/test_snippets_run.py
index cccf342b..aa7a7994 100644
--- a/harness/tests/prompts/test_snippets_run.py
+++ b/harness/tests/prompts/test_snippets_run.py
@@ -91,7 +91,7 @@ def _build_urdf_example(tmp_path, tag: str, model_py: str, urdf: str):
"""Run a doc example through the REAL urdf_blender pipeline (lint → Blender export →
FK consistency → collision sweep) — the build the agent's own files go through."""
from codeverse.config import get_settings
- from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+ from codeverse.languages.urdf import UrdfBlenderRuntime
from codeverse.workspace import Workspace
if not get_settings().resolve_blender():
diff --git a/harness/tests/prompts/test_snippets_static.py b/harness/tests/prompts/test_snippets_static.py
index fc708f7d..4340973b 100644
--- a/harness/tests/prompts/test_snippets_static.py
+++ b/harness/tests/prompts/test_snippets_static.py
@@ -91,7 +91,7 @@ def test_xml_examples_follow_the_enforced_frame_recipe(rel: str, tmp_path) -> No
consistency rule the build enforces: meshes hold WORLD coordinates, so FK(q=0) of a
link composed with its visual origin is the identity (visual origin = −link frame).
This is the recipe the reviewer found the docs contradicting (visual origin 0 0 0)."""
- from codeverse.languages.urdf.lint import lint_urdf_text
+ from codeverse.languages.urdf import lint_urdf_text
from codeverse.spatial.joints import fk, load_urdf
checked = 0
diff --git a/harness/tests/scene_gates/conftest.py b/harness/tests/scene_gates/conftest.py
index f0970f33..e5eb8a2f 100644
--- a/harness/tests/scene_gates/conftest.py
+++ b/harness/tests/scene_gates/conftest.py
@@ -6,7 +6,7 @@ from pathlib import Path
import pytest
-from codeverse.languages.scene_threejs.skeleton import write_example
+from codeverse.languages.scene_threejs import write_example
from codeverse.workspace import Workspace
diff --git a/harness/tests/scene_prompts/test_prompt_assembler_contract.py b/harness/tests/scene_prompts/test_prompt_assembler_contract.py
index 9812e11d..4eafedab 100644
--- a/harness/tests/scene_prompts/test_prompt_assembler_contract.py
+++ b/harness/tests/scene_prompts/test_prompt_assembler_contract.py
@@ -14,7 +14,7 @@ import re
import pytest
from codeverse.contracts.plan import CameraPlan
-from codeverse.languages.scene_threejs.assemble import render_scene_js
+from codeverse.languages.scene_threejs import render_scene_js
from codeverse.prompts import load_text
CAMS = [CameraPlan(name="Establishing", position=(1.0, 2.0, 3.0), look_at=(0.0, 1.0, 0.0), fov=44.0)]
@@ -64,7 +64,7 @@ def test_env_prompt_teaches_ctx_signature_and_update(env_prompt: str) -> None:
def test_env_prompt_sun_azimuth_matches_the_assembler_regex(env_prompt: str) -> None:
- from codeverse.languages.scene_threejs.assemble import _SUN_RE
+ from codeverse.languages.scene_threejs import _SUN_RE
example = re.search(r"`?export const SUN_AZIMUTH_DEG[^`\n]*", env_prompt)
assert example, "env prompt must show the export the assembler looks for"
diff --git a/harness/tests/scene_runtime/conftest.py b/harness/tests/scene_runtime/conftest.py
index 5540e802..a6038714 100644
--- a/harness/tests/scene_runtime/conftest.py
+++ b/harness/tests/scene_runtime/conftest.py
@@ -10,7 +10,7 @@ from pathlib import Path
import pytest
from codeverse.config import get_settings
-from codeverse.languages.scene_threejs.skeleton import write_example
+from codeverse.languages.scene_threejs import write_example
from codeverse.workspace import Workspace
RUNTIME_JS = get_settings().runtime_js_dir()
diff --git a/harness/tests/scene_runtime/test_assemble.py b/harness/tests/scene_runtime/test_assemble.py
index 24409d7a..44773f35 100644
--- a/harness/tests/scene_runtime/test_assemble.py
+++ b/harness/tests/scene_runtime/test_assemble.py
@@ -7,15 +7,15 @@ import math
import pytest
from codeverse.contracts.plan import CameraPlan
-from codeverse.languages.scene_threejs.assemble import (
+from codeverse.languages.scene_threejs import (
ZoneProbe,
assemble,
cameras_from_specs,
+ lint,
probe_zone_modules,
render_scene_js,
sun_azimuth,
)
-from codeverse.languages.scene_threejs.lint import lint
from tests.scene_runtime.conftest import needs_browser, needs_node
BOX_A = {"min": [-10, 0, -10], "max": [10, 6, 10], "size": [20, 6, 20]}
diff --git a/harness/tests/scene_runtime/test_lint.py b/harness/tests/scene_runtime/test_lint.py
index fd131be3..c1d74641 100644
--- a/harness/tests/scene_runtime/test_lint.py
+++ b/harness/tests/scene_runtime/test_lint.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import pytest
from codeverse.contracts.artifacts import Severity
-from codeverse.languages.scene_threejs.lint import lint
+from codeverse.languages.scene_threejs import lint
from tests.scene_runtime.conftest import needs_node
pytestmark = [pytest.mark.node, needs_node]
diff --git a/harness/tests/scene_runtime/test_runtime.py b/harness/tests/scene_runtime/test_runtime.py
index 597d91c0..6f9e9cab 100644
--- a/harness/tests/scene_runtime/test_runtime.py
+++ b/harness/tests/scene_runtime/test_runtime.py
@@ -9,7 +9,7 @@ import pytest
from codeverse.contracts.common import Language
from codeverse.languages import get_runtime
from codeverse.languages.base import LanguageRuntime
-from codeverse.languages.scene_threejs.runtime import SceneThreeJsRuntime
+from codeverse.languages.scene_threejs import SceneThreeJsRuntime
from tests.scene_runtime.conftest import needs_browser
@@ -22,7 +22,7 @@ def test_runtime_registered_and_conforms():
doc = rt.contract_doc()
assert "createScene" in doc and "update(t, dt)" in doc
# the built-in fallback contract is always available and carries the GLSL rules
- from codeverse.languages.scene_threejs import runtime as rt_mod
+ import codeverse.languages.scene_threejs as rt_mod
fallback = (rt_mod._HERE / "CONTRACT.md").read_text()
assert "createScene" in fallback and "#include" in fallback
assert rt.cookbook_path().name == "cookbook.md"
@@ -71,7 +71,7 @@ def test_build_interprets_combined_summary_offline(ws, monkeypatch):
"""The single-boot build (probe_scene.mjs --compile) still yields the SAME two
GateReports: scene_probe from the probe summary, shader_preflight from the
embedded shader_report; a non-booting scene keeps the failed-empty shader gate."""
- import codeverse.languages.scene_threejs.runtime as rt_mod
+ import codeverse.languages.scene_threejs as rt_mod
from codeverse.spatial.render_scene import NodeResult
calls: list[list[str]] = []
diff --git a/harness/tests/scene_runtime/test_skeleton.py b/harness/tests/scene_runtime/test_skeleton.py
index ffd9cf51..2d8a15ea 100644
--- a/harness/tests/scene_runtime/test_skeleton.py
+++ b/harness/tests/scene_runtime/test_skeleton.py
@@ -3,8 +3,7 @@
from __future__ import annotations
from codeverse.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan
-from codeverse.languages.scene_threejs.lint import lint
-from codeverse.languages.scene_threejs.skeleton import STARTER_DIR, write_example, write_skeleton
+from codeverse.languages.scene_threejs import STARTER_DIR, lint, write_example, write_skeleton
from tests.scene_runtime.conftest import needs_node
diff --git a/harness/tests/threejs_render/conftest.py b/harness/tests/threejs_render/conftest.py
index 37c95c32..096c9a1f 100644
--- a/harness/tests/threejs_render/conftest.py
+++ b/harness/tests/threejs_render/conftest.py
@@ -103,7 +103,7 @@ def stool_glb(tmp_path_factory: pytest.TempPathFactory) -> Path:
"""Build the stool once per session (needs node); skipped when node is missing."""
if shutil.which("node") is None:
pytest.skip("node not available")
- from codeverse.languages.threejs.runtime import ThreeJsRuntime
+ from codeverse.languages.threejs import ThreeJsRuntime
ws = write_stool(tmp_path_factory.mktemp("stool_session"))
res = ThreeJsRuntime().build(ws)
diff --git a/harness/tests/threejs_render/test_build.py b/harness/tests/threejs_render/test_build.py
index 628d81d5..10db5041 100644
--- a/harness/tests/threejs_render/test_build.py
+++ b/harness/tests/threejs_render/test_build.py
@@ -9,7 +9,7 @@ import numpy as np
import pytest
import trimesh
-from codeverse.languages.threejs.runtime import ThreeJsRuntime
+from codeverse.languages.threejs import ThreeJsRuntime
from codeverse.workspace import Workspace
pytestmark = pytest.mark.node
diff --git a/harness/tests/threejs_render/test_error_routing.py b/harness/tests/threejs_render/test_error_routing.py
index 4c95a487..215b9816 100644
--- a/harness/tests/threejs_render/test_error_routing.py
+++ b/harness/tests/threejs_render/test_error_routing.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from pathlib import Path
-from codeverse.languages.threejs.runtime import ThreeJsRuntime
+from codeverse.languages.threejs import ThreeJsRuntime
from codeverse.spatial.node import NodeResult
from codeverse.workspace import Workspace
diff --git a/harness/tests/threejs_render/test_lint.py b/harness/tests/threejs_render/test_lint.py
index 6bd5160f..041996de 100644
--- a/harness/tests/threejs_render/test_lint.py
+++ b/harness/tests/threejs_render/test_lint.py
@@ -6,10 +6,10 @@ from pathlib import Path
import pytest
+import codeverse.languages.threejs as lint_mod
from codeverse.contracts.artifacts import Severity
from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
-from codeverse.languages.threejs import lint as lint_mod
-from codeverse.languages.threejs.lint import lint_workspace
+from codeverse.languages.threejs import lint_workspace
from codeverse.workspace import Workspace
diff --git a/harness/tests/threejs_render/test_skeleton.py b/harness/tests/threejs_render/test_skeleton.py
index 73791090..0c2a71e9 100644
--- a/harness/tests/threejs_render/test_skeleton.py
+++ b/harness/tests/threejs_render/test_skeleton.py
@@ -7,8 +7,7 @@ from pathlib import Path
import pytest
from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
-from codeverse.languages.threejs.runtime import ThreeJsRuntime
-from codeverse.languages.threejs.skeleton import write_skeleton
+from codeverse.languages.threejs import ThreeJsRuntime, write_skeleton
from codeverse.workspace import Workspace
diff --git a/harness/tests/threejs_render/test_stale_outputs.py b/harness/tests/threejs_render/test_stale_outputs.py
index 51e2279f..aa68e979 100644
--- a/harness/tests/threejs_render/test_stale_outputs.py
+++ b/harness/tests/threejs_render/test_stale_outputs.py
@@ -11,8 +11,8 @@ import json
import pytest
-import codeverse.languages.threejs.runtime as rt_mod
-from codeverse.languages.threejs.runtime import ThreeJsRuntime
+import codeverse.languages.threejs as rt_mod
+from codeverse.languages.threejs import ThreeJsRuntime
from codeverse.spatial.node import NodeError, NodeResult
from codeverse.workspace import Workspace
diff --git a/harness/tests/urdf_joints/test_consistency.py b/harness/tests/urdf_joints/test_consistency.py
index d0fe8565..93f4578b 100644
--- a/harness/tests/urdf_joints/test_consistency.py
+++ b/harness/tests/urdf_joints/test_consistency.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from codeverse.contracts.artifacts import Severity
-from codeverse.languages.urdf.consistency import check_fk_consistency
+from codeverse.languages.urdf import check_fk_consistency
from codeverse.spatial.joints import load_urdf
from tests.urdf_joints.conftest import write_mesh_robot
diff --git a/harness/tests/urdf_joints/test_lint.py b/harness/tests/urdf_joints/test_lint.py
index 03093875..d513a4fd 100644
--- a/harness/tests/urdf_joints/test_lint.py
+++ b/harness/tests/urdf_joints/test_lint.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from codeverse.contracts.artifacts import Severity
-from codeverse.languages.urdf.lint import lint_model_text, lint_urdf_text, lint_workspace
+from codeverse.languages.urdf import lint_model_text, lint_urdf_text, lint_workspace
from codeverse.workspace import Workspace
GOOD = """<?xml version="1.0"?>
diff --git a/harness/tests/urdf_joints/test_live_blender.py b/harness/tests/urdf_joints/test_live_blender.py
index cf17e1f4..92a81c74 100644
--- a/harness/tests/urdf_joints/test_live_blender.py
+++ b/harness/tests/urdf_joints/test_live_blender.py
@@ -6,7 +6,7 @@ import numpy as np
import pytest
from codeverse.config import get_settings
-from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+from codeverse.languages.urdf import UrdfBlenderRuntime
from codeverse.spatial.joints import (
ARTICULATION_SHEET_NAME,
blender_render_glb,
@@ -122,7 +122,7 @@ def test_wrapper_unsafe_link_name_is_a_build_error(tmp_path):
import json as _json
import subprocess
- from codeverse.languages.urdf.runtime import WRAPPER
+ from codeverse.languages.urdf import WRAPPER
(tmp_path / "robot.urdf").write_text('<robot name="r"><link name="../evil"/></robot>')
(tmp_path / "model.py").write_text("import bpy\n")
diff --git a/harness/tests/urdf_joints/test_runtime_offline.py b/harness/tests/urdf_joints/test_runtime_offline.py
index 8d8b9561..7f80cb36 100644
--- a/harness/tests/urdf_joints/test_runtime_offline.py
+++ b/harness/tests/urdf_joints/test_runtime_offline.py
@@ -7,10 +7,10 @@ from types import SimpleNamespace
import pytest
+import codeverse.languages.urdf as rt_mod
from codeverse.contracts.common import Language
from codeverse.languages import get_runtime
-from codeverse.languages.urdf import runtime as rt_mod
-from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+from codeverse.languages.urdf import UrdfBlenderRuntime
from codeverse.proc import ProcResult
from codeverse.workspace import Workspace
from tests.urdf_joints.conftest import box_glb
diff --git a/harness/tests/urdf_joints/test_skeleton.py b/harness/tests/urdf_joints/test_skeleton.py
index e8fbfc61..447db591 100644
--- a/harness/tests/urdf_joints/test_skeleton.py
+++ b/harness/tests/urdf_joints/test_skeleton.py
@@ -8,9 +8,10 @@ import numpy as np
import pytest
from codeverse.contracts.plan import ArticulatedPlan, BBox, JointPlan, PartPlan
-from codeverse.languages.urdf.lint import lint_model_text, lint_urdf_text
-from codeverse.languages.urdf.skeleton import (
+from codeverse.languages.urdf import (
compute_urdf_frames,
+ lint_model_text,
+ lint_urdf_text,
render_model_py,
render_urdf,
write_skeleton,
@@ -99,7 +100,7 @@ def test_write_skeleton(tmp_path, drawer_plan):
def test_skeleton_rejects_static_plan(tmp_path):
from codeverse.contracts.plan import StaticPlan
- from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+ from codeverse.languages.urdf import UrdfBlenderRuntime
sp = StaticPlan(object_name="x", summary="s", overall_bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)),
parts=[PartPlan(name="A", role="r", description="d", bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)))])